SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2109.08359 · EMNLP · 2021

Distilling Linguistic Context for Language Model Compression

Eunho Yang, Kaist, Korea, South Daejeon, Geondo Park, Gyeongman Kim

arXiv · PDF · Open in the Atlas

Code that ran

8 of 11 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; 0 honoured the contract we drafted, 0 violated it and 7 have no contract verdict; 1 failure 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/2109.08359.json · badge: /api/ran/2109.08359.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
geondopark/ckd canonical (classifier label)
classifier basis: census
6 ran · 3 no recorded run
GeondoPark/CKD community
Papers with Code archive
2 ran · 0 no recorded run
FunctionStatusWhere it lives
WR_Dist Ran
ran on a synthesized input
GeondoPark/CKD/loss.py
code served (permissive licence) · get_code("b800b685392b45f9")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 0, 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
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

def batch_pairwise_squared_distance(x, squared=False):
    bsz, max_len, dim = x.size()
    x_sq = (x ** 2).sum(dim=2)
    prod = torch.bmm(x, x.transpose(1, 2))
    dist = (x_sq.unsqueeze(1) + x_sq.unsqueeze(2) - 2 * prod).clamp(min=1e-12)
    if squared == True:
        dist = torch.sqrt(dist).clone()
    dist[:, range(max_len), range(max_len)] = 0
    return dist

class WR_Dist(nn.Module):

    def __init__(self):
        super(WR_Dist, self).__init__()

    def forward(self, t_embed, s_embed, attention_mask, distance, lossfunc, normalize=False, squard=False):
        bsz, layer_num, max_len, dim = t_embed.size()
        _, _, _, sdim = s_embed.size()
        t_embed = t_embed.view(-1, max_len, dim)
        s_embed = s_embed.view(-1, max_len, sdim)
        mask = self.make_mask(attention_mask, layer_num)
        mask = mask.view(-1, max_len, max_len)
        with torch.no_grad():
            if distance == 'cos':
                t_norm = F.normalize(t_embed, p=2, dim=2)
                t_d = torch.bmm(t_norm, t_norm.transpose(1, 2))
                t_d = t_d * mask
                diagonal = (torch.ones(max_len, max_len) - torch.eye(max_len, max_len)).to(t_embed.device)
                t_d = t_d.masked_fill(diagonal == 0, -np.inf)
                t_d = t_d.masked_fill(mask == 0, -np.inf)
                t_d = F.softmax(t_d, dim=-1)
                t_d = t_d * mask
            elif distance == 'l2':
                t_d = batch_pairwise_squared_distance(t_embed, squared=False)
                if normalize:
                    t_d = t_d * mask
                    nonzero = torch.sum(t_d.view(bsz * layer_num, -1) > 0, dim=-1)
                    mean_td = t_d.view(bsz * layer_num, -1).sum(dim=-1) / nonzero
                    t_d = t_d / mean_td.unsqueeze(1).unsqueeze(2)
                else:
                    t_d = t_d * mask
        if distance == 'cos':
            s_norm = F.normalize(s_embed, p=2, dim=2)
            s_d = torch.bmm(s_norm, s_norm.transpose(1, 2))
            s_d = s_d * mask
            s_d = s_d.masked_fill(diagonal == 0, -np.inf)
            s_d = s_d.masked_fill(mask == 0, -np.inf)
            s_d = F.log_softmax(s_d, dim=-1)
            s_d = s_d * mask
        elif distance == 'l2':
            s_d = batch_pairwise_squared_distance(s_embed, squared=False)
            if normalize:
                s_d = s_d * mask
                nonzero = torch.sum(s_d.view(bsz * layer_num, -1) > 0, dim=-1)
                mean_sd = s_d.view(bsz * layer_num, -1).sum(dim=-1) / nonzero
                s_d = s_d / mean_sd.unsqueeze(1).unsqueeze(2)
            else:
                s_d = s_d * mask
        if lossfunc == 'kldiv':
            return F.kl_div(s_d, t_d, reduction='sum') / mask.sum().item()
        elif lossfunc == 'l1loss':
            return F.l1_loss(s_d, t_d, reduction='sum') / mask.sum().item()
        elif lossfunc == 'l2loss':
            return F.mse_loss(s_d, t_d, reduction='sum') / mask.sum().item()
        elif lossfunc == 'smoothl1':
            return F.smooth_l1_loss(s_d, t_d, reduction='sum') / mask.sum().item()

    def make_mask(self, attention_mask, layers):
        mask = attention_mask.unsqueeze(2) * attention_mask.unsqueeze(1)
        return mask.unsqueeze(1).repeat(1, layers, 1, 1).float()


INIT_ARGS = {}

ARGS = {
    't_embed': torch.randn(2, 2, 3, 4),
    's_embed': torch.randn(2, 2, 3, 5),
    'attention_mask': torch.ones(2, 3),
    'distance': 'l2',
    'lossfunc': 'l2loss',
    'normalize': False,
    'squard': False,
}

if __name__ == '__main__':
    model = WR_Dist(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output: {output}")
    print(f"Output type: {type(output)}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 0, dtype family float — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
batch_pairwise_squared_distance Ran
ran; our contract draft was wrong, not the code
GeondoPark/CKD/loss.py
code served (permissive licence) · get_code("86c8ee1f21537ab4")
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 Tensor, ndim 3, dtype family float, shape (2, 3, 3) 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

torch.manual_seed(0)

# Construct a small tensor: batch_size=2, max_len=3, dim=4
x = torch.randn(2, 3, 4)

ARGS = {
    "x": x,
    "squared": False
}
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 Tensor, ndim 3, dtype family float, shape (2, 3, 3) — shape (2, 3, 3) 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
central_squared_distance Ran
ran on a synthesized input
geondopark/ckd/loss.py
code served (permissive licence) · get_code("5f120c1844e683ad")
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 Tensor, ndim 3, dtype family float, shape (2, 3, 5) 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

torch.manual_seed(0)

# The function expects x to be a 4D tensor with shape (bsz, max_len, w_size, dim)
# bsz: batch size
# max_len: maximum sequence length
# w_size: window size (must be odd to have a valid center)
# dim: dimension of each element

bsz = 2
max_len = 3
w_size = 5  # odd number so center = (5-1)/2 = 2
dim = 4

# Create a random tensor of the expected shape
x = torch.randn(bsz, max_len, w_size, dim)

ARGS = {
    'x': x,
    'squared': False
}
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 Tensor, ndim 3, dtype family float, shape (2, 3, 5) — shape (2, 3, 5) 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
change_args Ran
ran on a synthesized input
geondopark/ckd/distil_config.py
code served (permissive licence) · get_code("e0dc53f0929c6449")
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 Args. The image it ran in was 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

torch.manual_seed(0)

class Args:
    def __init__(self):
        self.task_name = 'cola'
        self.alpha = 0.5
        self.temperature = 2.0
        self.wrdist_w = 1
        self.wtrdist_w = 1
        self.wrangle_w = 10
        self.wtrangle_w = 10
        self.learning_rate = 1e-4
        self.num_train_epochs = 3
        self.eval_steps = 50

ARGS = {
    'args': Args()
}
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 Args — a Args output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a Args output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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
get_eval_metric Ran
ran on a synthesized input
geondopark/ckd/glue_train.py
code served (permissive licence) · get_code("fee2c1995f150225")
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
import numpy as np

torch.manual_seed(0)

# The function takes task_name (str) and results (dict)
# It looks up a metric_name based on task_name, then accesses results[metric_name]
# and returns (current_eval, metric_name)

# Let's use 'cola' as the task_name, which maps to metric_name='mcc'
task_name = 'cola'
metric_name = 'mcc'

# results needs to be a dict with the metric as a key
# The value should be a numeric evaluation metric
results = {
    'mcc': 0.85,
    'mnli/acc': 0.90,
    'mnli-mm/acc': 0.88,
    'f1': 0.92,
    'acc': 0.89,
    'spearmanr': 0.87
}

ARGS = {
    'task_name': task_name,
    'results': results
}
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, 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
prepare_embedding_retrieval Ran
ran on a synthesized input
geondopark/ckd/data_augment.py
code served (permissive licence) · get_code("d0e10e804efa302e")
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. 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 numpy as np
import tempfile
import os

# Create a temporary GloVe-format file for testing
temp_dir = tempfile.mkdtemp()
glove_file = os.path.join(temp_dir, "glove_test.txt")

# Write a small GloVe format file with embeddings
with open(glove_file, 'w', encoding='utf-8') as f:
    # Write some sample word embeddings (word followed by vector values)
    f.write("the 0.1 0.2 0.3 0.4\n")
    f.write("a 0.5 0.6 0.7 0.8\n")
    f.write("cat 0.9 1.0 1.1 1.2\n")
    f.write("dog 1.3 1.4 1.5 1.6\n")
    f.write("bird 1.7 1.8 1.9 2.0\n")
    f.write("<unk> 0.0 0.0 0.0 0.0\n")
    # Add more dummy entries to reach vocab_size if needed
    for i in range(6, 100):
        f.write(f"word{i} {float(i*0.1)} {float(i*0.2)} {float(i*0.3)} {float(i*0.4)}\n")

ARGS = {
    "glove_file": glove_file,
    "vocab_size": 100
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy — 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
strip_accents Ran
ran on a synthesized input
geondopark/ckd/data_augment.py
code served (permissive licence) · get_code("22fcb8611ccd6b38")
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 str. The image it ran in was 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 unicodedata

def strip_accents(text):
    """
    Strip accents from input String.
    :param text: The input string.
    :type text: String.
    :returns: The processed String.
    :rtype: String.
    """
    try:
        text = unicode(text, 'utf-8')
    except (TypeError, NameError):
        pass
    text = unicodedata.normalize('NFD', text)
    text = text.encode('ascii', 'ignore')
    text = text.decode('utf-8')
    return str(text)

ARGS = {
    'text': 'Héllo Wørld café'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
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 str — a str output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a str output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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
window_index Ran
ran on a synthesized input
geondopark/ckd/loss.py
code served (permissive licence) · get_code("115c66fe58517dd8")
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 Tensor, ndim 3, dtype family float, shape (2, 4, 5) 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

torch.manual_seed(0)

ARGS = {
    "w_size": 5,
    "bsz": 2,
    "length": 4
}
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 Tensor, ndim 3, dtype family float, shape (2, 4, 5) — shape (2, 4, 5) 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
load_squad_dataset Not yet run
unverified (harvested, no recorded run)
geondopark/ckd/dataset.py
code served (permissive licence) · get_code("97abae8d9724c599")
How it ran

no invocation recorded.

matching_alignment Not yet run
unverified (harvested, no recorded run)
geondopark/ckd/utils.py
code served (permissive licence) · get_code("de26a43a3cba0208")
How it ran

no invocation recorded.

set_experiments Not yet run
unverified (harvested, no recorded run)
geondopark/ckd/utils.py
code served (permissive licence) · get_code("1894e97f23292978")
How it ran

no invocation recorded.

Also present in other papers' code

Of 11 samples lifted from this paper's linked repositories, 11 carry a function identity and 0 do not. Of the 11 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 11 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.

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

A computationally expensive and memory intensive neural network lies behind the recent success of language representation learning. Knowledge distillation, a major technique for deploying such a vast language model in resource-scarce environments, transfers the knowledge on individual word representations learned without restrictions. In this paper, inspired by the recent observations that language representations are relatively positioned and have more semantic knowledge as a whole, we present a new knowledge distillation objective for language representation learning that transfers the contextual knowledge via two types of relationships across representations: Word Relation and Layer Transforming Relation. Unlike other recent distillation techniques for the language models, our contextual distillation does not have any restrictions on architectural changes between teacher and student. We validate the effectiveness of our method on challenging benchmarks of language understanding tasks, not only in architectures of various sizes, but also in combination with DynaBERT, the recently proposed adaptive size pruning method.

For agents

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

get_harvested_code_for_paper("2109.08359")
get_code_for_paper("2109.08359")
have("2109.08359")

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

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

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

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

Connect an agent — have() is free.