SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2305.06535 · ACL · 2023

KGA: A General Machine Unlearning Framework Based on Knowledge Gap Alignment

Tong Chen, Wei Yuan, Xingshan Zeng, Kam-Fai Wong, Hongzhi Yin, Lingzhi Wang

arXiv · PDF · Open in the Atlas

Code that ran

7 of 9 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, 1 violated it and 6 have no contract verdict; 0 failures of our instrument; 2 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/2305.06535.json · badge: /api/ran/2305.06535.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
lingzhi-wang/kgaunlearn canonical (classifier label)
classifier basis: census
7 ran · 2 no recorded run
FunctionStatusWhere it lives
convert_examples_to_features Ran
ran on a synthesized input
lingzhi-wang/kgaunlearn/classification/utils.py
code served (permissive licence) · get_code("6b3716364a307c21")
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 TensorDataset. 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
from transformers import AutoTokenizer

torch.manual_seed(0)

# Create a minimal tokenizer stand-in
class MinimalTokenizer:
    def __init__(self):
        self.cls_token = "[CLS]"
        self.sep_token = "[SEP]"
        self.pad_token = "[PAD]"
        self._token_to_id = {
            "[CLS]": 101,
            "[SEP]": 102,
            "[PAD]": 0,
            "hello": 103,
            "world": 104,
            "test": 105,
            "example": 106,
        }
    
    def tokenize(self, text):
        # Simple tokenization: split on spaces
        words = text.split()
        tokens = []
        for word in words:
            if word in self._token_to_id:
                tokens.append(word)
            else:
                tokens.append("test")
        return tokens
    
    def convert_tokens_to_ids(self, tokens):
        return [self._token_to_id.get(token, 0) for token in tokens]

# Create example data
examples = [
    {"txt": "hello world", "label": 1},
    {"txt": "test example", "label": 0},
]

tokenizer = MinimalTokenizer()
max_seq_length = 16

ARGS = {
    "examples": examples,
    "max_seq_length": max_seq_length,
    "tokenizer": tokenizer,
    "cls_token_at_end": False,
    "cls_token_segment_id": 0,
    "sep_token_extra": False,
    "pad_on_left": False,
    "pad_token_segment_id": 0,
    "sequence_segment_id": 0,
    "mask_padding_with_zero": True,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type TensorDataset — a TensorDataset 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
dev_loop Ran
ran on a synthesized input
lingzhi-wang/kgaunlearn/response/run_generation.py
code served (permissive licence) · get_code("ab1fc5c157f23c1e")
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 torch.nn as nn

torch.manual_seed(0)

# Create a minimal model that returns outputs with a .loss attribute
class MinimalModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 2)
    
    def forward(self, input_ids, **kwargs):
        logits = self.linear(input_ids)
        loss = logits.mean()
        
        # Create a simple output object with a loss attribute
        class OutputContainer:
            pass
        
        outputs = OutputContainer()
        outputs.loss = loss
        return outputs

# Create a minimal dataloader
# Each batch should be a dict-like object that can be moved to device and unpacked with **
class BatchDict(dict):
    def to(self, device):
        # Return a new BatchDict with tensors moved to device
        return BatchDict({k: v.to(device) if isinstance(v, torch.Tensor) else v 
                         for k, v in self.items()})

# Create sample batches
batch1 = BatchDict({'input_ids': torch.randn(2, 4)})
batch2 = BatchDict({'input_ids': torch.randn(2, 4)})
dataloader = [batch1, batch2]

# Create model
model = MinimalModel()

# Create args with device set to CPU
class Args:
    device = 'cpu'

args = Args()

ARGS = {
    'args': args,
    'dataloader': dataloader,
    'model': model
}
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 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
evaluate_multilabels Ran
ran on a synthesized input
lingzhi-wang/kgaunlearn/classification/utils.py
code served (permissive licence) · get_code("340d2237f9509870")
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 defaultdict. 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.

from typing import List, Dict, DefaultDict
from collections import defaultdict

# Construct test data for evaluate_multilabels
# The function expects:
# - y: List[List[str]] - gold labels (multilabel)
# - y_preds: List[List[str]] - predicted labels (multilabel)
# - do_print: bool - whether to print results

y = [
    ['label_a', 'label_b'],
    ['label_b', 'label_c'],
    ['label_a', 'label_c'],
    ['label_b'],
]

y_preds = [
    ['label_a', 'label_b'],
    ['label_b'],
    ['label_a', 'label_d'],
    ['label_a', 'label_b', 'label_c'],
]

ARGS = {
    'y': y,
    'y_preds': y_preds,
    'do_print': False,
}
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 defaultdict — a defaultdict output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a defaultdict 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_dataLoader Ran
ran on a synthesized input
lingzhi-wang/kgaunlearn/response/data.py
code served (permissive licence) · get_code("9d89819a5e128380")
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 DataLoader. 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
from torch.utils.data import Dataset
from transformers import BatchEncoding

torch.manual_seed(0)

# Small stand-in classes and objects
class SimpleTokenizer:
    def __init__(self):
        self.eos_token_id = 2
        self.vocab = {
            '<|endoftext|>': 0,
            '[PAD]': 1,
            '[EOS]': 2,
            'hello': 3,
            'world': 4,
            'test': 5,
        }
        self.id_to_token = {v: k for k, v in self.vocab.items()}
    
    def tokenize(self, text):
        # Simple whitespace tokenization
        words = text.split()
        tokens = []
        for word in words:
            if word in self.vocab:
                tokens.append(word)
            else:
                tokens.append('test')  # fallback
        return tokens if tokens else ['test']
    
    def convert_tokens_to_ids(self, tokens):
        return [self.vocab.get(t, 5) for t in tokens]
    
    def __call__(self, texts, padding=False, max_length=None, truncation=False, return_tensors=None):
        # Mimics tokenizer call for labels
        ids = []
        for text in texts if isinstance(texts, list) else [texts]:
            token_ids = self.convert_tokens_to_ids(self.tokenize(text))
            if max_length and len(token_ids) > max_length:
                token_ids = token_ids[:max_length]
            if padding and max_length:
                token_ids = token_ids + [1] * (max_length - len(token_ids))
            ids.append(token_ids)
        
        if return_tensors == 'pt':
            ids = torch.LongTensor(ids)
        
        return {'input_ids': ids}
    
    def as_target_tokenizer(self):
        return self

class SimpleModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 4)
    
    def prepare_decoder_input_ids_from_labels(self, labels):
        # Return shifted labels (standard seq2seq decoder input)
        return labels.clone()

class SimpleDataset(Dataset):
    def __init__(self):
        self.data = [
            {'src': 'hello world<|endoftext|>test', 'tgt': 'output one'},
            {'src': 'world test<|endoftext|>hello', 'tgt': 'output two'},
        ]
    
    def __len__(self):
        return len(self.data)
    
    def __getitem__(self, idx):
        return self.data[idx]

class SimpleArgs:
    def __init__(self):
        self.batch_size = 2
        self.max_target_length = 5

# Construct arguments
args = SimpleArgs()
dataset = SimpleDataset()
model = SimpleModel()
tokenizer = SimpleTokenizer()

ARGS = {
    'args': args,
    'dataset': dataset,
    'model': model,
    'tokenizer': tokenizer,
    'batch_size': None,
    'shuffle': False,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch, transformers — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type DataLoader — a DataLoader output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataLoader 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_dataLoader Ran
ran on a synthesized input
lingzhi-wang/kgaunlearn/translation/data.py
code served (permissive licence) · get_code("c6c0c0019eebe367")
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 DataLoader. 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
from torch.utils.data import Dataset

torch.manual_seed(0)

# Create a minimal args object
class Args:
    def __init__(self):
        self.max_input_length = 32
        self.max_target_length = 16
        self.batch_size = 2

# Create a minimal dataset
class MinimalDataset(Dataset):
    def __init__(self, size=4):
        self.size = size
    
    def __len__(self):
        return self.size
    
    def __getitem__(self, idx):
        return {
            'src': f'source text {idx}',
            'tgt': f'target text {idx}'
        }

# Create a minimal tokenizer (single tokenizer case)
class MinimalTokenizer:
    def __init__(self):
        self.pad_token_id = 0
        self.eos_token_id = 2
    
    def __call__(self, texts, padding=False, max_length=None, truncation=False, return_tensors=None):
        # Return a dict with input_ids
        batch_size = len(texts) if isinstance(texts, list) else 1
        seq_len = max_length if max_length else 10
        input_ids = torch.randint(0, 100, (batch_size, seq_len))
        attention_mask = torch.ones(batch_size, seq_len)
        
        result = {
            'input_ids': input_ids,
            'attention_mask': attention_mask
        }
        return result
    
    def as_target_tokenizer(self):
        return self

# Create a minimal model
class MinimalModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(4, 4)
    
    def prepare_decoder_input_ids_from_labels(self, labels):
        # Shift labels right by 1 position
        decoder_input_ids = labels.clone()
        decoder_input_ids[:, 1:] = labels[:, :-1]
        decoder_input_ids[:, 0] = 2  # eos_token_id
        return decoder_input_ids

args = Args()
dataset = MinimalDataset(size=4)
model = MinimalModel()
tokenizer = MinimalTokenizer()

ARGS = {
    'args': args,
    'dataset': dataset,
    'model': model,
    'tokenizer': tokenizer,
    'batch_size': None,
    'shuffle': 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 DataLoader — a DataLoader output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a DataLoader 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
multihot Ran
ran on a synthesized input
lingzhi-wang/kgaunlearn/classification/utils.py
code served (permissive licence) · get_code("d0417cd78cab8469")
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 ndarray, ndim 1, dtype family float, shape (4,) 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 numpy as np

# Construct arguments for the multihot function
labels = ["cat", "dog", "bird"]
label_map = {"cat": 0, "dog": 1, "bird": 2, "fish": 3}

ARGS = {
    "labels": labels,
    "label_map": label_map,
}
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 ndarray, ndim 1, dtype family float, shape (4,) — shape (4,) 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
sigmoid Ran
ran, violated the contract we drafted
lingzhi-wang/kgaunlearn/classification/run_classification.py
pointer only (licence: MIT); the stored copy get_code serves, from XPixelGroup/SEAL, is pointer only (licence: NONE) · get_code("f35babe3912ec8b1")
How it ran

The body of this sample is withheld: this paper's link allows the body inline (MIT), but get_code serves the stored copy, first harvested from XPixelGroup/SEAL, and GitHub detected no licence in that repository when it was checked. The setup block that called it is withheld with it, because it is written against that body. source_path and origin say where the code lives, to read under the repository's own terms. A run is recorded.

evaluate Not yet run
unverified (harvested, no recorded run)
lingzhi-wang/kgaunlearn/classification/run_classification.py
code served (permissive licence) · get_code("2f6edd20b524ee65")
How it ran

no invocation recorded.

train_loop Not yet run
unverified (harvested, no recorded run)
lingzhi-wang/kgaunlearn/response/run_generation.py
code served (permissive licence) · get_code("72c0db7655ddb2d6")
How it ran

no invocation recorded.

Also present in other papers' code

Of 9 samples lifted from this paper's linked repositories, 9 carry a function identity and 0 do not. Of the 9 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 8 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
sigmoid 12 other papers
5 dated earlier, 7 later · 1 only as an assembly brick
1506.02640 (2015-06)
You Only Look Once: Unified, Real-Time Object Detection
1602.01783 (2016-02)
Asynchronous Methods for Deep Reinforcement Learning
2106.12930 (2021-06)
VinDr-SpineXR: A deep learning framework for spinal lesions detection and classification from radiographs
and 9 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

Recent legislation of the "right to be forgotten" has led to the interest in machine unlearning, where the learned models are endowed with the function to forget information about specific training instances as if they have never existed in the training set. Previous work mainly focuses on computer vision scenarios and largely ignores the essentials of unlearning in NLP field, where text data contains more explicit and sensitive personal information than images. In this paper, we propose a general unlearning framework called KGA to induce forgetfulness. Different from previous work that tries to recover gradients or forces models to perform close to one specific distribution, KGA maintains distribution differences (i.e., knowledge gap). This relaxes the distribution assumption. Furthermore, we first apply the unlearning method to various NLP tasks (i.e., classification, translation, response generation) and propose several unlearning evaluation metrics with pertinence. Experiments on large-scale datasets show that KGA yields comprehensive improvements over baselines, where extensive analyses further validate the effectiveness of KGA and provide insight into unlearning for NLP tasks 1 .

For agents

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

get_harvested_code_for_paper("2305.06535")
get_code_for_paper("2305.06535")
have("2305.06535")

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

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

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

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

Connect an agent — have() is free.