SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2104.07858 · EMNLP · 2021

Matching-oriented Product Quantization For Ad-hoc Retrieval

Zheng Liu, Shitao Xiao, Defu Lian, Xing Xie, Yingxia Shao

arXiv · PDF · Open in the Atlas

Code that ran

5 of 8 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 1 honoured the contract we drafted, 1 violated it and 0 have no contract verdict; 3 failures of our instrument; 3 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2104.07858.json · badge: /api/ran/2104.07858.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
microsoft/MoPQ canonical (classifier label)
classifier basis: census
5 ran · 3 no recorded run
FunctionStatusWhere it lives
compute_acc Ran
ran; our contract draft was wrong, not the code
microsoft/MoPQ/utils/utils.py
code served (permissive licence) · get_code("4702e60a1d1a3d53")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Create small tensors for testing
# scores: shape (batch_size, num_classes) - logits/scores for each class
# labels: shape (batch_size,) - ground truth labels
batch_size = 2
num_classes = 4

scores = torch.randn(batch_size, num_classes)
labels = torch.tensor([1, 3], dtype=torch.long)

ARGS = {
    "scores": scores,
    "labels": labels,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
compute_retrive_acc Ran
ran; our contract draft was wrong, not the code
microsoft/MoPQ/utils/utils.py
code served (permissive licence) · get_code("39961e2ee77414a7")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch

torch.manual_seed(0)

# Create small tensors for q and k
# q and k are used in torch.matmul(q, k.transpose(0, 1))
# So q should be shape (batch, dim) and k should be shape (batch, dim)
batch_size = 2
dim = 4

q = torch.randn(batch_size, dim)
k = torch.randn(batch_size, dim)

# Create masks
# mask_q and mask_k are used in operations like mask_q * mask_k and mask.unsqueeze(0)
# They should be broadcastable with batch_size
mask_q = torch.ones(batch_size, dtype=torch.long)
mask_k = torch.ones(batch_size, dtype=torch.long)

ARGS = {
    "q": q,
    "k": k,
    "mask_q": mask_q,
    "mask_k": mask_k,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
str2bool Ran
ran, violated the contract we drafted
microsoft/MoPQ/parameters.py
code served (permissive licence) · get_code("7c508037b40522af")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned bool, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import argparse

def str2bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

# Test cases for str2bool
ARGS = {
    'v': 'true'  # string input that should convert to boolean
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
none outside the standard library — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type bool, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
tokenize_and_infer Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
microsoft/MoPQ/preprocess.py
code served (permissive licence) · get_code("6e9e257967094a66")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple. The image it ran in was not recorded. The code mentions cuda, and the harness aliases cuda to the CPU for every sample; whether this run needed that is not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import numpy as np

torch.manual_seed(0)

class MockTokenizer:
    def batch_encode_plus(self, texts, add_special_tokens=False, padding=False, truncation=False, max_length=None):
        # Return mock token IDs and attention masks
        batch_size = len(texts)
        seq_length = max_length if max_length else 10
        return {
            'input_ids': [[101] * seq_length for _ in range(batch_size)],
            'attention_mask': [[1] * seq_length for _ in range(batch_size)]
        }

class MockModel(nn.Module):
    def __init__(self, hidden_dim=4):
        super().__init__()
        self.hidden_dim = hidden_dim
        self.linear_q = nn.Linear(10, hidden_dim)
        self.linear_k = nn.Linear(10, hidden_dim)
    
    def infer_q(self, input_ids, attention_mask):
        # Simulate inference: return batch_size x hidden_dim tensor
        batch_size = input_ids.shape[0]
        dummy_hidden = torch.randn(batch_size, self.hidden_dim)
        return dummy_hidden
    
    def infer_k(self, input_ids, attention_mask):
        # Simulate inference: return batch_size x hidden_dim tensor
        batch_size = input_ids.shape[0]
        dummy_hidden = torch.randn(batch_size, self.hidden_dim)
        return dummy_hidden

tokenizer = MockTokenizer()
model = MockModel(hidden_dim=4)

batch_query = ["hello world", "how are you"]
batch_key = ["goodbye world", "farewell"]
input_query_vec = True
input_key_vec = True
max_query_length = 20
max_key_length = 15

ARGS = {
    'batch_query': batch_query,
    'batch_key': batch_key,
    'input_query_vec': input_query_vec,
    'input_key_vec': input_key_vec,
    'max_query_length': max_query_length,
    'max_key_length': max_key_length,
    'tokenizer': tokenizer,
    'model': model
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
warmup_linear Ran
ran, honoured the contract we drafted
microsoft/MoPQ/utils/utils.py
code served (permissive licence) · get_code("e8dcf12045bcc046")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned float, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np

class Args:
    def __init__(self):
        self.warmup_step = 1000
        self.schedule_step = 5000

ARGS = {
    'args': Args(),
    'step': 500
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type float, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
encode Not yet run
unverified (harvested, no recorded run)
microsoft/MoPQ/utils/recall.py
code served (permissive licence) · get_code("29dc941df1dc58d2")
How it ran

no invocation recorded.

get_result_by_dtable Not yet run
unverified (harvested, no recorded run)
microsoft/MoPQ/utils/recall.py
code served (permissive licence) · get_code("25fcf1c155aabad7")
How it ran

no invocation recorded.

recall_by_dtable Not yet run
unverified (harvested, no recorded run)
microsoft/MoPQ/utils/recall.py
code served (permissive licence) · get_code("4381c8db6a0cb61e")
How it ran

no invocation recorded.

Also present in other papers' code

Of 8 samples lifted from this paper's linked repositories, 8 carry a function identity and 0 do not. Of the 8 distinct functions with an identity, 1 are also present in other papers whose code we hold (1 with at least one paper dated earlier, 0 the same month, 1 later) and 7 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
str2bool 175 other papers
27 dated earlier, 148 later · 2 only as an assembly brick
1406.6247 (2014-06)
Recurrent Models of Visual Attention
1603.09382 (2016-03)
Deep Networks with Stochastic Depth
1710.10196 (2017-10)
Progressive Growing of GANs for Improved Quality, Stability, and Variation
and 172 more not named here

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Product quantization (PQ) is a widely used technique for ad-hoc retrieval. Recent studies propose supervised PQ, where the embedding and quantization models can be jointly trained with supervised learning. However, there is a lack of appropriate formulation of the joint training objective; thus, the improvements over previous non-supervised baselines are limited in reality. In this work, we propose the Matching-oriented Product Quantization (MoPQ), where a novel objective Multinoulli Contrastive Loss (MCL) is formulated. With the minimization of MCL, we are able to maximize the matching probability of query and ground-truth key, which contributes to the optimal retrieval accuracy. Given that the exact computation of MCL is intractable due to the demand of vast contrastive samples, we further propose the Differentiable Cross-device Sampling (DCS), which significantly augments the contrastive samples for precise approximation of MCL. We conduct extensive experimental studies on four realworld datasets, whose results verify the effectiveness of MoPQ. The code is available at https://github.com/microsoft/MoPQ. †. Work is done during the internship at Microsoft. * . Corresponding author. 1. We adopt the Asymmetric Distance Computation (ADC) (Jégou et al., 2011), where only keys need to be quantized.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2104.07858")
get_code_for_paper("2104.07858")
have("2104.07858")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2104.07858.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2104.07858.svg)](https://syntology.ai/paper/2104.07858)

Connect an agent — have() is free.