SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2406.12975 · EMNLP · 2024

SHIELD: Evaluation and Defense Strategies for Copyright Compliance in LLM Text Generation

Xiaoqian Wang, Jing Gao, Feijie Wu, Cunxiang Wang, Xiaoze Liu, Ting Sun, Tianyang Xu, Mrs Dursley

arXiv · PDF · Open in the Atlas

Code that ran

2 of 2 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 2 have no contract verdict; 0 failures of our instrument; 0 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/2406.12975.json · badge: /api/ran/2406.12975.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
xz-liu/shield marked official in Papers with Code
Papers with Code archive
2 ran · 0 no recorded run
FunctionStatusWhere it lives
NGramLogitsProcessor Ran
ran on a synthesized input
xz-liu/shield/shield/models.py
code served (permissive licence) · get_code("f46cc6d76949f841")
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
from collections import defaultdict
from transformers import AutoTokenizer
from unittest.mock import MagicMock

# Create a minimal tokenizer mock
tokenizer = MagicMock()
tokenizer.pad_token_id = 0
tokenizer.eos_token_id = 1
tokenizer.convert_tokens_to_ids = MagicMock(side_effect=lambda x: {'\t': 2, '\n': 3, '\r': 4}.get(x, 5))
tokenizer.encode = MagicMock(return_value=[0, 1, 2, 3])
tokenizer.batch_encode_plus = MagicMock(return_value={'input_ids': [[0, 1, 2]]})

# Create a minimal NgramModel
class NgramModel:
    def __init__(self, n, tokenizer, dataset_name):
        self.context_size = n - 1
        self.ngram_counts = defaultdict(int)
        self.context_counts = defaultdict(int)
        self.n = n
        self.tokenizer = tokenizer
        self.dataset_name = dataset_name

    def remove_special_tokens(self, input_ids):
        tokenizer = self.tokenizer
        tab_token_id = tokenizer.convert_tokens_to_ids('\t')
        newline_token_id = tokenizer.convert_tokens_to_ids('\n')
        carriage_return_token_id = tokenizer.convert_tokens_to_ids('\r')
        special_tokens = {tab_token_id, newline_token_id, carriage_return_token_id}
        new_input_ids = [token_id for token_id in input_ids if token_id not in special_tokens]
        if isinstance(input_ids, torch.Tensor):
            return torch.tensor(new_input_ids)
        return new_input_ids

    def get_prob(self, context, tokens_list):
        if isinstance(context, torch.Tensor):
            context = context.tolist()
        if isinstance(tokens_list, torch.Tensor):
            tokens_list = tokens_list.tolist()
        if len(context) < self.n - 1:
            return [0] * len(tokens_list)
        elif len(context) > self.n - 1:
            context = context[-(self.n - 1):]
        context = tuple(context)
        if self.context_counts[context] == 0:
            return [0] * len(tokens_list)
        return [self.ngram_counts[context + (token,)] / self.context_counts[context] for token in tokens_list]

    @property
    def vocab(self):
        return set((token for context_plus_token in self.ngram_counts for token in context_plus_token))

# Create ngram model instance
ngram_model = NgramModel(n=3, tokenizer=tokenizer, dataset_name="test")

# Populate with some dummy data
ngram_model.context_counts[(0, 1)] = 10
ngram_model.ngram_counts[(0, 1, 5)] = 3
ngram_model.ngram_counts[(0, 1, 6)] = 7

# Import the class
from transformers import LogitsProcessor

class NGramLogitsProcessor(LogitsProcessor):
    def __init__(self, ngram_model: NgramModel, is_vllm: bool=False, tokenizer=None):
        self.ngram_model = ngram_model
        self.alpha = 0.1
        self.tokenizer = tokenizer
        self.ngram_hits_count = 0
        self.is_vllm = is_vllm
        self.prompt_token_ids = 'None'
        self.reset_ngram_hits()

    def reset_ngram_hits(self):
        self.ngram_hits_count = 0
        self.ngram_hits_tokens = []

    @torch.no_grad()
    def log_ngram_hits(self, ngram_values: torch.Tensor):
        hits = ngram_values > 1e-06
        if torch.any(hits):
            self.ngram_hits_count += 1
            return True
        return False

    def process_last_token_logits_no_batch(self, input_ids, processed_logits):
        possible_tokens = processed_logits.topk(k=10, dim=-1).indices
        input_ids = input_ids.flatten()
        new_input_ids = self.ngram_model.remove_special_tokens(input_ids)
        ngram_logits_for_possible_tokens = self.ngram_model.get_prob(new_input_ids, possible_tokens.flatten())
        ngram_logits = torch.tensor(ngram_logits_for_possible_tokens).to(processed_logits.device).to(processed_logits.dtype)
        self.log_ngram_hits(ngram_logits)
        processed_logits = processed_logits.view(-1)
        possible_tokens = possible_tokens.view(-1)
        alpha = self.alpha
        processed_logits[possible_tokens] = processed_logits[possible_tokens] * (1 - ngram_logits)
        processed_logits = processed_logits.view(1, -1)
        return processed_logits

    def __call__(self, input_ids, logits):
        return self.process_last_token_logits_no_batch(input_ids, logits)

INIT_ARGS = {
    'ngram_model': ngram_model,
    'is_vllm': False,
    'tokenizer': tokenizer,
}

ARGS = {
    'input_ids': torch.tensor([[0, 1, 5, 6]]),
    'logits': torch.randn(1, 50257),
}

METHOD = '__call__'

if __name__ == '__main__':
    processor = NGramLogitsProcessor(**INIT_ARGS)
    result = processor(**ARGS)
    print("Result shape:", result.shape)
    print("NGram hits count:", processor.ngram_hits_count)
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch, tqdm, transformers — 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)
NgramModel Ran
ran on a synthesized input
xz-liu/shield/shield/models.py
code served (permissive licence) · get_code("25f26c6a9fe11966")
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 NoneType. 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 collections import defaultdict
from unittest.mock import Mock

# Create a minimal mock tokenizer
tokenizer = Mock()
tokenizer.pad_token_id = 0
tokenizer.eos_token_id = 1
tokenizer.convert_tokens_to_ids = Mock(side_effect=lambda x: {'\t': 2, '\n': 3, '\r': 4}.get(x, 5))

INIT_ARGS = {
    'n': 3,
    'tokenizer': tokenizer,
    'dataset_name': 'test_dataset'
}

# Create a small tokenized corpus for training
tokenized_corpus = [
    torch.tensor([[5, 6, 7, 8, 9]]),
    torch.tensor([[10, 11, 12, 13]]),
]

ARGS = {
    'tokenized_corpus': tokenized_corpus
}

METHOD = 'train'

# Construct and call
if __name__ == '__main__':
    from tqdm import tqdm
    
    # Import the class (assuming it's defined above or in the same file)
    class NgramModel:

        def __init__(self, n, tokenizer, dataset_name):
            print('N of ngram model is [{}]'.format(n))
            self.context_size = n - 1
            self.ngram_counts = defaultdict(int)
            self.context_counts = defaultdict(int)
            self.n = n
            self.tokenizer = tokenizer
            self.dataset_name = dataset_name

        def remove_special_tokens(self, input_ids):
            tokenizer = self.tokenizer
            tab_token_id = tokenizer.convert_tokens_to_ids('\t')
            newline_token_id = tokenizer.convert_tokens_to_ids('\n')
            carriage_return_token_id = tokenizer.convert_tokens_to_ids('\r')
            special_tokens = {tab_token_id, newline_token_id, carriage_return_token_id}
            new_input_ids = [token_id for token_id in input_ids if token_id not in special_tokens]
            if isinstance(input_ids, torch.Tensor):
                return torch.tensor(new_input_ids)
            return new_input_ids

        def train(self, tokenized_corpus):
            tokenizer = self.tokenizer
            for input_ids in tqdm(tokenized_corpus, desc='Training ngram model'):
                input_ids = input_ids.flatten().tolist()
                input_ids = self.remove_special_tokens(input_ids)
                sentence = [tokenizer.pad_token_id] * (self.n - 1) + input_ids + [tokenizer.eos_token_id]
                for i in range(len(sentence) - self.n + 1):
                    context = tuple(sentence[i:i + self.n - 1])
                    token = sentence[i + self.n - 1]
                    self.ngram_counts[tuple(context + (token,))] += 1
                    self.context_counts[context] += 1

        def get_prob(self, context, tokens_list):
            if isinstance(context, torch.Tensor):
                context = context.tolist()
            if isinstance(tokens_list, torch.Tensor):
                tokens_list = tokens_list.tolist()
            if len(context) < self.n - 1:
                return [0] * len(tokens_list)
            elif len(context) > self.n - 1:
                context = context[-(self.n - 1):]
            context = tuple(context)
            if self.context_counts[context] == 0:
                return [0] * len(tokens_list)
            return [self.ngram_counts[context + (token,)] / self.context_counts[context] for token in tokens_list]

        @property
        def vocab(self):
            return set((token for context_plus_token in self.ngram_counts for token in context_plus_token))

    model = NgramModel(**INIT_ARGS)
    getattr(model, METHOD)(**ARGS)
    print("Training complete. Vocab size:", len(model.vocab))
    print("Sample ngram counts:", dict(list(model.ngram_counts.items())[:3]))
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch, tqdm — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type NoneType — a NoneType output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a NoneType 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: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)

Also present in other papers' code

Of 2 samples lifted from this paper's linked repositories, 2 carry a function identity and 0 do not. Of the 2 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 2 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

Large Language Models (LLMs) have transformed machine learning but raised significant legal concerns due to their potential to produce text that infringes on copyrights, resulting in several high-profile lawsuits. The legal landscape is struggling to keep pace with these rapid advancements, with ongoing debates about whether generated text might plagiarize copyrighted materials. Current LLMs may infringe on copyrights or overly restrict non-copyrighted texts, leading to these challenges: (i) the need for a comprehensive evaluation benchmark to assess copyright compliance from multiple aspects; (ii) evaluating robustness against safeguard bypassing attacks; and (iii) developing effective defenses targeted against the generation of copyrighted text. To tackle these challenges, we introduce a curated dataset to evaluate methods, test attack strategies, and propose lightweight, a real-time defense mechanism to prevent the generation of copyrighted text, ensuring the safe and lawful use of LLMs. Our experiments demonstrate that current LLMs frequently output copyrighted text, and that jailbreaking attacks can significantly increase the volume of copyrighted output. Our proposed defense mechanism significantly reduce the volume of copyrighted text generated by LLMs by effectively refusing malicious requests.

For agents

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

get_harvested_code_for_paper("2406.12975")
get_code_for_paper("2406.12975")
have("2406.12975")

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

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

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

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

Connect an agent — have() is free.