Skip to content

Commit

Permalink
Twitter Recommendation Algorithm
Browse files Browse the repository at this point in the history
Please note we have force-pushed a new initial commit in order to remove some publicly-available Twitter user information. Note that this process may be required in the future.
  • Loading branch information
twitter-team committed Mar 31, 2023
0 parents commit ef4c5eb
Show file tree
Hide file tree
Showing 5,364 changed files with 460,239 additions and 0 deletions.
The diff you're trying to view is too large. We only load the first 3000 changed files.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.DS_Store

661 changes: 661 additions & 0 deletions COPYING

Large diffs are not rendered by default.

39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Twitter Recommendation Algorithm

The Twitter Recommendation Algorithm is a set of services and jobs that are responsible for constructing and serving the
Home Timeline. For an introduction to how the algorithm works, please refer to our [engineering blog](https://blog.twitter.com/engineering/en_us/topics/open-source/2023/twitter-recommendation-algorithm). The
diagram below illustrates how major services and jobs interconnect.

![](docs/system-diagram.png)

These are the main components of the Recommendation Algorithm included in this repository:

| Type | Component | Description |
|------------|------------|------------|
| Feature | [simclusters-ann](simclusters-ann/README.md) | Community detection and sparse embeddings into those communities. |
| | [TwHIN](https://github.com/twitter/the-algorithm-ml/blob/main/projects/twhin/README.md) | Dense knowledge graph embeddings for Users and Tweets. |
| | [trust-and-safety-models](trust_and_safety_models/README.md) | Models for detecting NSFW or abusive content. |
| | [real-graph](src/scala/com/twitter/interaction_graph/README.md) | Model to predict likelihood of a Twitter User interacting with another User. |
| | [tweepcred](src/scala/com/twitter/graph/batch/job/tweepcred/README) | Page-Rank algorithm for calculating Twitter User reputation. |
| | [recos-injector](recos-injector/README.md) | Streaming event processor for building input streams for [GraphJet](https://github.com/twitter/GraphJet) based services. |
| | [graph-feature-service](graph-feature-service/README.md) | Serves graph features for a directed pair of Users (e.g. how many of User A's following liked Tweets from User B). |
| Candidate Source | [search-index](src/java/com/twitter/search/README.md) | Find and rank In-Network Tweets. ~50% of Tweets come from this candidate source. |
| | [cr-mixer](cr-mixer/README.md) | Coordination layer for fetching Out-of-Network tweet candidates from underlying compute services. |
| | [user-tweet-entity-graph](src/scala/com/twitter/recos/user_tweet_entity_graph/README.md) (UTEG)| Maintains an in memory User to Tweet interaction graph, and finds candidates based on traversals of this graph. This is built on the [GraphJet](https://github.com/twitter/GraphJet) framework. Several other GraphJet based features and candidate sources are located [here](src/scala/com/twitter/recos) |
| | [follow-recommendation-service](follow-recommendations-service/README.md) (FRS)| Provides Users with recommendations for accounts to follow, and Tweets from those accounts. |
| Ranking | [light-ranker](src/python/twitter/deepbird/projects/timelines/scripts/models/earlybird/README.md) | Light ranker model used by search index (Earlybird) to rank Tweets. |
| | [heavy-ranker](https://github.com/twitter/the-algorithm-ml/blob/main/projects/home/recap/README.md) | Neural network for ranking candidate tweets. One of the main signals used to select timeline Tweets post candidate sourcing. |
| Tweet mixing & filtering | [home-mixer](home-mixer/README.md) | Main service used to construct and serve the Home Timeline. Built on [product-mixer](product-mixer/README.md) |
| | [visibility-filters](visibilitylib/README.md) | Responsible for filtering Twitter content to support legal compliance, improve product quality, increase user trust, protect revenue through the use of hard-filtering, visible product treatments, and coarse-grained downranking. |
| | [timelineranker](timelineranker/README.md) | Legacy service which provides relevance-scored tweets from the Earlybird Search Index and UTEG service. |
| Software framework | [navi](navi/navi/README.md) | High performance, machine learning model serving written in Rust. |
| | [product-mixer](product-mixer/README.md) | Software framework for building feeds of content. |
| | [twml](twml/README.md) | Legacy machine learning framework built on TensorFlow v1. |

We include Bazel BUILD files for most components, but not a top level BUILD or WORKSPACE file.

## Contributing

We invite the community to submit GitHub issues and pull requests for suggestions on improving the recommendation algorithm. We are working on tools to manage these suggestions and sync changes to our internal repository. Any security concerns or issues should be routed to our official [bug bounty program](https://hackerone.com/twitter) through HackerOne. We hope to benefit from the collective intelligence and expertise of the global community in helping us identify issues and suggest improvements, ultimately leading to a better Twitter.

Read our blog on the open source initiative [here](https://blog.twitter.com/en_us/topics/company/2023/a-new-era-of-transparency-for-twitter).
15 changes: 15 additions & 0 deletions ann/src/main/java/com/twitter/ann/faiss/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
target(
name = "faiss",
dependencies = [
"ann/src/main/java/com/twitter/ann/faiss/swig:swig-artifactory",
],
)

java_library(
name = "swig-native-utils",
sources = ["*.java"],
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [],
)
151 changes: 151 additions & 0 deletions ann/src/main/java/com/twitter/ann/faiss/NativeUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package com.twitter.ann.faiss;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Locale;

public final class NativeUtils {

private static final int MIN_PREFIX_LENGTH = 3;
public static final String NATIVE_FOLDER_PATH_PREFIX = "nativeutils";

public static File temporaryDir;

private NativeUtils() {
}

private static File unpackLibraryFromJarInternal(String path) throws IOException {
if (null == path || !path.startsWith("/")) {
throw new IllegalArgumentException("The path has to be absolute (start with '/').");
}

String[] parts = path.split("/");
String filename = (parts.length > 1) ? parts[parts.length - 1] : null;

if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {
throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
}

if (temporaryDir == null) {
temporaryDir = createTempDirectory(NATIVE_FOLDER_PATH_PREFIX);
temporaryDir.deleteOnExit();
}

File temp = new File(temporaryDir, filename);

try (InputStream is = NativeUtils.class.getResourceAsStream(path)) {
Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
temp.delete();
throw e;
} catch (NullPointerException e) {
temp.delete();
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
}

return temp;
}

/**
* Unpack library from JAR into temporary path
*
* @param path The path of file inside JAR as absolute path (beginning with
* '/'), e.g. /package/File.ext
* @throws IOException If temporary file creation or read/write
* operation fails
* @throws IllegalArgumentException If source file (param path) does not exist
* @throws IllegalArgumentException If the path is not absolute or if the
* filename is shorter than three characters
* (restriction of
* {@link File#createTempFile(java.lang.String, java.lang.String)}).
* @throws FileNotFoundException If the file could not be found inside the
* JAR.
*/
public static void unpackLibraryFromJar(String path) throws IOException {
unpackLibraryFromJarInternal(path);
}

/**
* Loads library from current JAR archive
* <p>
* The file from JAR is copied into system temporary directory and then loaded.
* The temporary file is deleted after
* exiting.
* Method uses String as filename because the pathname is "abstract", not
* system-dependent.
*
* @param path The path of file inside JAR as absolute path (beginning with
* '/'), e.g. /package/File.ext
* @throws IOException If temporary file creation or read/write
* operation fails
* @throws IllegalArgumentException If source file (param path) does not exist
* @throws IllegalArgumentException If the path is not absolute or if the
* filename is shorter than three characters
* (restriction of
* {@link File#createTempFile(java.lang.String, java.lang.String)}).
* @throws FileNotFoundException If the file could not be found inside the
* JAR.
*/
public static void loadLibraryFromJar(String path) throws IOException {
File temp = unpackLibraryFromJarInternal(path);

try (InputStream is = NativeUtils.class.getResourceAsStream(path)) {
Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
temp.delete();
throw e;
} catch (NullPointerException e) {
temp.delete();
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
}

try {
System.load(temp.getAbsolutePath());
} finally {
temp.deleteOnExit();
}
}

private static File createTempDirectory(String prefix) throws IOException {
String tempDir = System.getProperty("java.io.tmpdir");
File generatedDir = new File(tempDir, prefix + System.nanoTime());

if (!generatedDir.mkdir()) {
throw new IOException("Failed to create temp directory " + generatedDir.getName());
}

return generatedDir;
}

public enum OSType {
Windows, MacOS, Linux, Other
}

protected static OSType detectedOS;

/**
* detect the operating system from the os.name System property and cache
* the result
*
* @returns - the operating system detected
*/
public static OSType getOperatingSystemType() {
if (detectedOS == null) {
String osname = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((osname.contains("mac")) || (osname.contains("darwin"))) {
detectedOS = OSType.MacOS;
} else if (osname.contains("win")) {
detectedOS = OSType.Windows;
} else if (osname.contains("nux")) {
detectedOS = OSType.Linux;
} else {
detectedOS = OSType.Other;
}
}
return detectedOS;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */

package com.twitter.ann.faiss;

public class AlignedTableFloat32 {
private transient long swigCPtr;
protected transient boolean swigCMemOwn;

protected AlignedTableFloat32(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}

protected static long getCPtr(AlignedTableFloat32 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}

@SuppressWarnings("deprecation")
protected void finalize() {
delete();
}

public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
swigfaissJNI.delete_AlignedTableFloat32(swigCPtr);
}
swigCPtr = 0;
}
}

public void setTab(SWIGTYPE_p_faiss__AlignedTableTightAllocT_float_32_t value) {
swigfaissJNI.AlignedTableFloat32_tab_set(swigCPtr, this, SWIGTYPE_p_faiss__AlignedTableTightAllocT_float_32_t.getCPtr(value));
}

public SWIGTYPE_p_faiss__AlignedTableTightAllocT_float_32_t getTab() {
long cPtr = swigfaissJNI.AlignedTableFloat32_tab_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_faiss__AlignedTableTightAllocT_float_32_t(cPtr, false);
}

public void setNumel(long value) {
swigfaissJNI.AlignedTableFloat32_numel_set(swigCPtr, this, value);
}

public long getNumel() {
return swigfaissJNI.AlignedTableFloat32_numel_get(swigCPtr, this);
}

public static long round_capacity(long n) {
return swigfaissJNI.AlignedTableFloat32_round_capacity(n);
}

public AlignedTableFloat32() {
this(swigfaissJNI.new_AlignedTableFloat32__SWIG_0(), true);
}

public AlignedTableFloat32(long n) {
this(swigfaissJNI.new_AlignedTableFloat32__SWIG_1(n), true);
}

public long itemsize() {
return swigfaissJNI.AlignedTableFloat32_itemsize(swigCPtr, this);
}

public void resize(long n) {
swigfaissJNI.AlignedTableFloat32_resize(swigCPtr, this, n);
}

public void clear() {
swigfaissJNI.AlignedTableFloat32_clear(swigCPtr, this);
}

public long size() {
return swigfaissJNI.AlignedTableFloat32_size(swigCPtr, this);
}

public long nbytes() {
return swigfaissJNI.AlignedTableFloat32_nbytes(swigCPtr, this);
}

public SWIGTYPE_p_float get() {
long cPtr = swigfaissJNI.AlignedTableFloat32_get__SWIG_0(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_float(cPtr, false);
}

public SWIGTYPE_p_float data() {
long cPtr = swigfaissJNI.AlignedTableFloat32_data__SWIG_0(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_float(cPtr, false);
}

}
Loading

14 comments on commit ef4c5eb

@raymond-design
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

me and the boys dislike .DS_Store

@Abdur-rahmaanJ
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They gitignored it in the next commits

@IgorKowalczyk
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A little too long file, too long :shipit:

@ayebrian
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too long cringe

@ayebrian
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

@ayebrian
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too long ig

@sanamhub
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

@sanamhub
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

@sanamhub
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

image

image

image

image

@sanamhub
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image
image

@alizardguy
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all my homies hate .DS_Store

@mauro-balades
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is crazy

@LewBr
Copy link

@LewBr LewBr commented on ef4c5eb Apr 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This source-code has so much content that it makes the page lag.

@mauro-balades
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This source-code has so much content that it makes the page lag.

Check out chromium's source code!

Please sign in to comment.