SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2203.03825 · ACL · 2022

Incorporating Hierarchy into Text Encoder: a Contrastive Learning Approach for Hierarchical Text Classification

Zihan Wang, Peiyi Wang, Xin Sun, Houfeng Wang, Lianzhe Huang

arXiv · PDF · Open in the Atlas

Code that ran

5 of 11 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (2 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 5 have no contract verdict; 0 failures of our instrument; 6 no recorded run), measured 2026-11-22; 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/2203.03825.json · badge: /api/ran/2203.03825.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
wzh9969/contrastive-htc community
Papers with Code archive
5 ran · 6 no recorded run
FunctionStatusWhere it lives
BartAttention Ran
ran on a synthesized input
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("9c1eae0a3959807d")
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 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 torch
import torch.nn as nn

INIT_ARGS = {
    'embed_dim': 8,
    'num_heads': 2,
    'dropout': 0.1,
    'is_decoder': False,
    'bias': True,
}

ARGS = {
    'hidden_states': torch.randn(2, 3, 8),
    'key_value_states': None,
    'past_key_value': None,
    'attention_mask': None,
    'output_attentions': False,
    'extra_attn': None,
    'only_attn': False,
}
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
BertEmbeddings Ran
ran on a synthesized input
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("dcc09c5532200722")
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 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 torch
import torch.nn as nn

class BertEmbeddings(nn.Module):
    """Construct the embeddings from word, position and token_type embeddings."""

    def __init__(self, config):
        super().__init__()
        self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
        self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
        self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.register_buffer('position_ids', torch.arange(config.max_position_embeddings).expand((1, -1)))
        self.position_embedding_type = getattr(config, 'position_embedding_type', 'absolute')

    def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0, embedding_weight=None):
        if input_ids is not None:
            input_shape = input_ids.size()
        else:
            input_shape = inputs_embeds.size()[:-1]
        seq_length = input_shape[1]
        if position_ids is None:
            position_ids = self.position_ids[:, past_key_values_length:seq_length + past_key_values_length]
        if token_type_ids is None:
            token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
        if inputs_embeds is None:
            inputs_embeds = self.word_embeddings(input_ids)
        if embedding_weight is not None:
            if len(embedding_weight.size()) == 2:
                embedding_weight = embedding_weight.unsqueeze(-1)
            inputs_embeds = inputs_embeds * embedding_weight
        token_type_embeddings = self.token_type_embeddings(token_type_ids)
        embeddings = inputs_embeds + token_type_embeddings
        if self.position_embedding_type == 'absolute':
            position_embeddings = self.position_embeddings(position_ids)
            embeddings += position_embeddings
        embeddings = self.LayerNorm(embeddings)
        embeddings = self.dropout(embeddings)
        return (embeddings, inputs_embeds)


class Config:
    def __init__(self):
        self.vocab_size = 100
        self.hidden_size = 4
        self.pad_token_id = 0
        self.max_position_embeddings = 16
        self.type_vocab_size = 2
        self.layer_norm_eps = 1e-12
        self.hidden_dropout_prob = 0.1
        self.position_embedding_type = 'absolute'


INIT_ARGS = {
    'config': Config()
}

ARGS = {
    'input_ids': torch.randint(1, 100, (2, 8), dtype=torch.long),
    'token_type_ids': None,
    'position_ids': None,
    'inputs_embeds': None,
    'past_key_values_length': 0,
    'embedding_weight': None
}

if __name__ == '__main__':
    model = BertEmbeddings(**INIT_ARGS)
    output = model(**ARGS)
    print("Output shapes:", output[0].shape, output[1].shape)
    print("Success!")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
BertOutputLayer Ran
ran on a synthesized input
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("ddb657076af7cea8")
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 2, 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

class BertOutputLayer(nn.Module):

    def __init__(self, config):
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)
        self.out_proj = nn.Linear(config.hidden_size, config.num_labels)

    def forward(self, x, **kwargs):
        x = self.dropout(x)
        x = self.dense(x)
        x = torch.tanh(x)
        x = self.dropout(x)
        x = self.out_proj(x)
        return x


class Config:
    def __init__(self, hidden_size, hidden_dropout_prob, num_labels):
        self.hidden_size = hidden_size
        self.hidden_dropout_prob = hidden_dropout_prob
        self.num_labels = num_labels


INIT_ARGS = {
    'config': Config(hidden_size=4, hidden_dropout_prob=0.1, num_labels=3)
}

ARGS = {
    'x': torch.randn(2, 4)
}

if __name__ == '__main__':
    model = BertOutputLayer(**INIT_ARGS)
    output = model(**ARGS)
    print(f"Output shape: {output.shape}")
    print(f"Output: {output}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
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 2, 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)
BertPoolingLayer Ran
ran on a synthesized input · constructed an object; no result was computed
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("ad00a3061aa7bdc2")
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 an instance of its own class, BertPoolingLayer: the run constructed the object and did not call it, so no result was computed. 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
import torch.nn as nn

torch.manual_seed(0)

# Create a minimal config object
class Config:
    def __init__(self):
        self.hidden_size = 4
        self.num_attention_heads = 2

config = Config()

ARGS = {
    'config': config,
    'avg': 'cls'
}
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 BertPoolingLayer — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a BertPoolingLayer 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
NTXent Ran
ran on a synthesized input · constructed an object; no result was computed
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("8e41bc17f38b83ea")
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 an instance of its own class, NTXent: the run constructed the object and did not call it, so no result was computed. 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
import torch.nn as nn
import numpy as np

torch.manual_seed(0)

class Config:
    def __init__(self):
        self.hidden_dropout_prob = 0.1
        self.hidden_size = 4

config = Config()

x = torch.randn(2, 4)

ARGS = {
    "config": config,
    "tau": 1.0
}
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 NTXent — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a NTXent 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
BaseModelOutputWithPoolingAndCrossAttentions Not yet run
unverified (harvested, no recorded run)
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("b13db2a9f4af0aa0")
How it ran

no invocation recorded.

BertModel Not yet run
unverified (harvested, no recorded run)
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("1b18fd412b5eaf7b")
How it ran

no invocation recorded.

ContrastModel Not yet run
unverified (harvested, no recorded run)
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("b93b85c4d9138224")
How it ran

no invocation recorded.

GraphEncoder Not yet run
unverified (harvested, no recorded run)
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("aa93cb13fe01f92c")
How it ran

no invocation recorded.

GraphLayer Not yet run
unverified (harvested, no recorded run)
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("da6ef7283c459235")
How it ran

no invocation recorded.

SelfAttention Not yet run
unverified (harvested, no recorded run)
wzh9969/contrastive-htc/model/contrast.py
code served (permissive licence) · get_code("985ecde4944a60ab")
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, 8 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 8 later) and 3 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
BartAttention
brick of this paper's assembly: helper
1 other paper
1 later · 1 only as an assembly brick
2603.15708 (2026-03)
Mastering the Minority: An Uncertainty-guided Multi-Expert Framework for Challenging-tailed Sequence Learning
BaseModelOutputWithPoolingAndCrossAttentions
brick of this paper's assembly: helper
1 other paper
1 later · 1 only as an assembly brick
2603.15708 (2026-03)
Mastering the Minority: An Uncertainty-guided Multi-Expert Framework for Challenging-tailed Sequence Learning
BertEmbeddings
brick of this paper's assembly: helper
1 other paper
1 later · 1 only as an assembly brick
2603.15708 (2026-03)
Mastering the Minority: An Uncertainty-guided Multi-Expert Framework for Challenging-tailed Sequence Learning
BertModel
brick of this paper's assembly: helper
1 other paper
1 later · 1 only as an assembly brick
2603.15708 (2026-03)
Mastering the Minority: An Uncertainty-guided Multi-Expert Framework for Challenging-tailed Sequence Learning
BertOutputLayer
brick of this paper's assembly: model
1 other paper
1 later · 1 only as an assembly brick
2603.15708 (2026-03)
Mastering the Minority: An Uncertainty-guided Multi-Expert Framework for Challenging-tailed Sequence Learning
GraphLayer
brick of this paper's assembly: helper
1 other paper
1 later · 1 only as an assembly brick
2603.15708 (2026-03)
Mastering the Minority: An Uncertainty-guided Multi-Expert Framework for Challenging-tailed Sequence Learning
NTXent
brick of this paper's assembly: loss
1 other paper
1 later · 1 only as an assembly brick
2603.15708 (2026-03)
Mastering the Minority: An Uncertainty-guided Multi-Expert Framework for Challenging-tailed Sequence Learning
SelfAttention
brick of this paper's assembly: helper
1 other paper
1 later · 1 only as an assembly brick
2603.15708 (2026-03)
Mastering the Minority: An Uncertainty-guided Multi-Expert Framework for Challenging-tailed Sequence Learning

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

Hierarchical text classification is a challenging subtask of multi-label classification due to its complex label hierarchy. Existing methods encode text and label hierarchy separately and mix their representations for classification, where the hierarchy remains unchanged for all input text. Instead of modeling them separately, in this work, we propose Hierarchyguided Contrastive Learning (HGCLR) to directly embed the hierarchy into a text encoder. During training, HGCLR constructs positive samples for input text under the guidance of the label hierarchy. By pulling together the input text and its positive sample, the text encoder can learn to generate the hierarchy-aware text representation independently. Therefore, after training, the HGCLR enhanced text encoder can dispense with the redundant hierarchy. Extensive experiments on three benchmark datasets verify the effectiveness of HGCLR.

For agents

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

get_harvested_code_for_paper("2203.03825")
get_code_for_paper("2203.03825")
have("2203.03825")

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

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

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

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

Connect an agent — have() is free.