Datasets:
Download environment/encode.py from jankin123/mle-leaking: direct link, hf CLI and curl.
- Browser
- Download file 3.37 kB
-
https://huggingface.co/datasets/jankin123/mle-leaking/resolve/main/environment/encode.py
- Command line
-
hf download hf://datasets/jankin123/mle-leaking/environment/encode.py
-
curl -L -o encode.py https://huggingface.co/datasets/jankin123/mle-leaking/resolve/main/environment/encode.py
3.37 kB
| """Encode portable messages without truncating any context or target text. | |
| Only the final assistant message receives loss. Requires a Qwen-compatible | |
| tokenizer containing the im_start/im_end tokens; never loads model weights. | |
| """ | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| TEMPLATE = "{% for m in messages %}{{ '<|im_start|>' + m['role'] + '\\n' + m['content'] + '<|im_end|>\\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}" | |
| def encode_row(row, tokenizer, max_length=262144): | |
| messages = row['messages'] | |
| assert messages[-1]['role'] == 'assistant' and messages[-1]['loss'] is True | |
| assert all(m['loss'] is False for m in messages[:-1]) | |
| clean = [dict(role=m['role'], content=m['content']) for m in messages] | |
| # This explicit serialization preserves whitespace and the published think | |
| # content exactly, without template-side reasoning stripping or trimming. | |
| prefix = tokenizer.apply_chat_template(clean[:-1], chat_template=TEMPLATE, | |
| tokenize=False, add_generation_prompt=True) | |
| full = tokenizer.apply_chat_template(clean, chat_template=TEMPLATE, | |
| tokenize=False, add_generation_prompt=False) | |
| assert full.startswith(prefix) | |
| suffix = full[len(prefix):] | |
| assert suffix == clean[-1]['content'] + '<|im_end|>\n' | |
| prefix_ids = tokenizer(prefix, add_special_tokens=False)['input_ids'] | |
| target_ids = tokenizer(suffix, add_special_tokens=False)['input_ids'] | |
| assert target_ids | |
| assert tokenizer.decode(target_ids, skip_special_tokens=False) == suffix | |
| assert tokenizer.decode(prefix_ids, skip_special_tokens=False) == prefix | |
| ids = prefix_ids + target_ids | |
| if len(ids) > max_length: | |
| raise ValueError(f'{row["sample_id"]}: {len(ids)} tokens exceed {max_length}; no truncation was performed') | |
| labels = [-100] * len(prefix_ids) + target_ids | |
| assert len(labels) == len(ids) and labels[len(prefix_ids):] == target_ids | |
| return dict(input_ids=ids, labels=labels, lengths=len(ids)), dict( | |
| context_tokens=len(prefix_ids), supervised_tokens=len(target_ids), total_tokens=len(ids)) | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--input', type=Path, required=True) | |
| parser.add_argument('--tokenizer', required=True) | |
| parser.add_argument('--output', type=Path, required=True) | |
| parser.add_argument('--max-length', type=int, default=262144) | |
| args = parser.parse_args() | |
| assert not args.output.exists(), 'Refuse to overwrite an encoded dataset' | |
| from transformers import AutoTokenizer | |
| from datasets import Dataset, Features, Sequence, Value | |
| tokenizer = AutoTokenizer.from_pretrained(args.tokenizer) | |
| for token in ('<|im_start|>', '<|im_end|>'): | |
| assert tokenizer.convert_tokens_to_ids(token) != tokenizer.unk_token_id | |
| def rows(): | |
| with args.input.open() as f: | |
| for line in f: | |
| encoded, _ = encode_row(json.loads(line), tokenizer, args.max_length) | |
| yield encoded | |
| features = Features(dict(input_ids=Sequence(Value('int32')), labels=Sequence(Value('int32')), lengths=Value('int32'))) | |
| dataset = Dataset.from_generator(rows, features=features) | |
| dataset.save_to_disk(str(args.output)) | |
| print(json.dumps(dict(rows=len(dataset), output=str(args.output), truncations=0))) | |
| if __name__ == '__main__': | |
| main() | |