Skip to main content

Cosine

UDTF: cugraph_cosine

Official cuGraph reference: C API

Compare the neighbor vectors of explicit vertex pairs using cosine similarity, with optional edge-weight contributions.

Quickstart​

The call below supplies edges from registered relation target_edges with canonical src and dst columns and may include weight, plus the registered relation candidate_pairs (the vertex_pairs relation with columns first, second). Substitute your own registered relations.

SELECT *
FROM cugraph_cosine(
edges => (SELECT src, dst FROM target_edges),
vertex_pairs => (SELECT first, second FROM candidate_pairs)
);

Inputs​

Every relation is a named parenthesized SELECT subquery. The required edges role uses canonical src and dst columns; every role, its canonical columns, and their accepted Arrow types are listed under Relation arguments. Metadata validation resolves registered tables named in its JSON request.

Endpoint columns accept numeric Int32, Int64 vertex IDs or logical string Utf8, LargeUtf8, Utf8View vertex IDs; string vertex-identity outputs are canonicalized to Utf8 (native mapping Int64) while scores, distances, counts, coordinates, and opaque labels stay numeric. The shared vertex-ID contract is summarized in Vertex ID support; the concrete call-specific schema comes from gpu_validate_call.

Logical string side-input limitations:

  • edge ID columns and edge-ID predicate side inputs are not supported for logical string graphs
  • candidate-pair columns must match the graph vertex domain; logical string graphs accept Utf8, LargeUtf8, or Utf8View independently per column

Arguments and options​

Relation arguments​

ArgumentRequiredColumnsDescription
edgesyes
  • src, dst: Int32, Int64, Utf8, LargeUtf8, Utf8View
  • weight (optional): Float32, Float64
  • edge_id (optional): Int32, Int64
edge relation with canonical src and dst columns, plus optional weight and edge_id columns
vertex_pairsyes
  • first, second: Int32, Int64, Utf8, LargeUtf8, Utf8View
explicit vertex pairs used by similarity scoring

Vertex columns of vertex_pairs must use the same vertex domain as edges: the integer type of src and dst, or any listed string type when the endpoints are strings. Every edge_id column must have the integer type of src and dst; string-keyed graphs accept no edge IDs.

Named value arguments​

This UDTF has no algorithm-specific value arguments. Its inputs are the relation arguments above and the graph construction options below.

Graph construction options​

This UDTF requires directed=false (undirected/symmetric graph); all other graph construction options follow the shared defaults documented in Graph Construction Options.

Output​

ColumnTypeNullableDescription
firstInt64|Utf8noFirst vertex from the explicit candidate-pair relation.
secondInt64|Utf8noSecond vertex from the explicit candidate-pair relation.
similarityFloat64noSimilarity coefficient for the explicit candidate pair.

These are generic descriptor schemas; run gpu_validate_call to get the concrete, table-specific output schema.

Examples​

This example runs on the citation network demo dataset.

Which papers share BERT's references despite different bibliography sizes?​

Compare BERT's 2018 reference list with NLP papers from 2015 through 2020 that have at least 10 references. Candidate papers use one of the listed field labels. For bibliographies A and B, the cosine score is |A ∩ B| / sqrt(|A| × |B|). Its denominator, the geometric mean of the two list sizes, accounts for bibliographies of different lengths.

The UDTF requires an undirected graph. Positive IDs represent citing papers, and negative IDs represent cited-paper reference roles. This keeps each positive paper ID adjacent only to negative IDs for its references; papers that cite BERT remain positive vertices. The edge projection omits weights, giving each reference a unit contribution. Candidate pairs exclude records whose title matches BERT's, avoiding title-identical editions as separate suggestions.

CREATE OR REPLACE VIEW similarity_seed AS
SELECT paper_id, title, n_references
FROM papers
WHERE title = 'BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding'
AND year = 2018;

CREATE OR REPLACE VIEW similarity_candidates AS
SELECT p.paper_id, p.title, p.n_references, p.year
FROM papers p
WHERE p.year BETWEEN 2015 AND 2020
AND p.n_references >= 10
AND p.primary_fos IN (
'Natural language processing', 'Language model',
'Machine translation', 'Question answering');

CREATE OR REPLACE VIEW bibliography_edges AS
SELECT e.src, -e.dst AS dst
FROM citation_edges e
JOIN (
SELECT paper_id FROM similarity_seed
UNION
SELECT paper_id FROM similarity_candidates
) selected ON selected.paper_id = e.src;

SELECT p.year, p.title, p.n_references,
ROUND(r.similarity, 3) AS cosine
FROM cugraph_cosine(
edges => (SELECT src, dst FROM bibliography_edges),
vertex_pairs => (
SELECT s.paper_id AS first, c.paper_id AS second
FROM similarity_seed s
CROSS JOIN similarity_candidates c
WHERE LOWER(c.title) <> LOWER(s.title)),
directed => false) r
JOIN papers p ON p.paper_id = r.second
ORDER BY r.similarity DESC, p.paper_id
LIMIT 5;
yeartitlen_referencescosine
2019MASS: Masked Sequence to Sequence Pre-training for Language Generation530.352
2019How to Fine-Tune BERT for Text Classification?.380.241
2019BoolQ: Exploring the Surprising Difficulty of Natural Yes/No Questions.350.228
2018Learning Cross-Lingual Sentence Representations via a Multi-task Dual-Encoder Model370.222
2019Surf at MEDIQA 2019: Improving Performance of Natural Language Inference in the Clinical Domain by Adopting Pre-trained Language Model.250.189

MASS and BERT share 19 references. BERT has 55 references in the graph and MASS has 53, so the score is 19 / sqrt(55 × 53) = 0.352.

The result ranks bibliography similarity; topic meaning is outside the score. For intersection divided by the union of references, see the Jaccard similarity example.

Limits​

  • similarity is explicit-pair only; all-pairs candidate generation and all-pairs top-k search are not exposed
  • vertex_pairs is a required relation with canonical first and second columns
  • candidate-pair columns must match the graph vertex domain; logical string graphs accept Utf8, LargeUtf8, or Utf8View independently per column
  • null candidate-pair values are rejected at execution and are never dropped
  • candidate pairs are a multiset: duplicate, reversed, and self pairs remain distinct output rows
  • result rows have no global ordering; use ORDER BY when order is required
  • providing edges.weight selects weighted similarity; omitting it selects unit-weight similarity
  • cuGraph requires directed=false so the graph is constructed as an undirected/symmetric view

To dry-run validate relation metadata, column types, and options without execution, see gpu_validate_call.