Run this model with HF Jobs
Run Jonnester/Purrence-3M on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/Jonnester/Purrence-3M. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Jonnester/Purrence-3M on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/Jonnester/Purrence-3M. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/Jonnester/Purrence-3M. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use Jonnester/Purrence-3M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Jonnester/Purrence-3M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Jonnester/Purrence-3M", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Jonnester/Purrence-3M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Jonnester/Purrence-3M with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Jonnester/Purrence-3M" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Jonnester/Purrence-3M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Jonnester/Purrence-3M
- SGLang
How to use Jonnester/Purrence-3M with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Jonnester/Purrence-3M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Jonnester/Purrence-3M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Jonnester/Purrence-3M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Jonnester/Purrence-3M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Jonnester/Purrence-3M with Docker Model Runner:
docker model run hf.co/Jonnester/Purrence-3M
Commit ·
921bf58
0
Parent(s):
Purrence-3M
Browse filesFiles changed (23)
- .gitattributesAdded+1
- README.mdAdded+195
- config.jsonAdded+27
- configuration_purrence.pyAdded+23
- evaluation_config.jsonAdded+131
- fast-attnres-LICENSEAdded+21
- load_model.pyAdded+37
- modded-nanogpt-LICENSEAdded+21
- model.safetensorsAdded+3
- modeling_purrence.pyAdded+68
- purrence_core.pyAdded+216
- purrence_runtime/__init__.pyAdded+1
- purrence_runtime/config.pyAdded+1
- purrence_runtime/model.pyAdded+1
- purrence_runtime/scorer.pyAdded+117
- purrence_runtime/tokenizer.pyAdded+1
- reproduce_evaluation.pyAdded+292
- requirements-eval.txtAdded+9
- requirements.txtAdded+4
- tokenization_purrence.pyAdded+63
- tokenizer/artifact.jsonAdded+10
- tokenizer/ordinary-tokenizer.jsonAdded
- tokenizer_config.jsonAdded+10
1*.safetensors filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195---tags: - purrence - text-generation - pytorch - safetensorslibrary_name: transformerspipeline_tag: text-generation---# Purrence-3M
I built Purrence as a base language model with 2,987,712 inference parameters and an 8,192 token context. I reuse one shared transformer block through six recurrent loops in a single pass, with Attention Residuals, half RoPE, document-aware key offsets, per-head XSA and sigmoid attention gates. I tie the embedding and output weights.
I include my FP32 inference weights, original tokenizer, native PyTorch loader and Transformers inference interface here. I use the model as a base language model without a chat template.
## My training blog
I share some of my training thoughts and other considerations in my blog, if you are interested in reading!
[Read my Purrence blog](https://jonathansu.me/#blogs/purrence)
## Model architecture
I spend most of my parameter budget on one wide transformer block and reuse it six times in a single pass. I use LR AttnRes to read earlier residual sources with learned depth queries. The block weights are shared across loops, while the queries let different reads select different mixtures of earlier representations.
| Field | Value ||---|---|| Inference parameters | 2,987,712 || Hidden size | 384 || Blocks | One shared block applied six times || Blocks stored / applied | 1 / 6 || Sequential passes | 1 || Intermediate size | 2,096 || Attention heads | 6 || Key and value heads | 6 || Head dimension | 64 || Attention | Causal multihead attention with QK normalization, per head XSA and sigmoid gates || Residual routing | LR AttnRes with rank 128 || Depth query bank | 12 learned queries of width 128, totaling 1,536 parameters || Activation | Squared ReLU in the backbone || Normalization | RMS normalization with epsilon `1e-6`. QK and routing normalization use `2^-23` || Positional encoding | Half RoPE on 32 of each head's 64 dimensions, with frequencies from 1 to 1/1,024 || Key offset | The unrotated key channels use the previous position within each document || Context length | 8,192 tokens || Vocabulary | 2,048 IDs, comprising 2,047 byte level BPE tokens and one structural boundary || Embeddings | Tied input and output, with 786,432 parameters || Logit cap | None || Released weights | FP32 Safetensors |
I normalize queries and keys before applying half RoPE. After causal attention, I use a learned XSA coefficient to adjust the component along the current token's value vector, then apply a learned sigmoid gate to each head. I use the tied embedding matrix for the final vocabulary projection.
During training, I used CE with NITP and a separate SwiGLU projector. That projector added 1,769,472 parameters, bringing the training total to 4,757,184. I discard it for inference, and it is absent from the weights in this repository. I trained with BF16 and evaluate the released weights in FP32.
## How I trained it
I based my training data on the Pulvis v2 mixture. I trained this checkpoint from scratch for 5B tokens, with a 4B token plateau followed by a 1B token cooldown. I kept this release at 5B because my follow-up benchmark experiments showed little benefit from training beyond 5B tokens. I treat that as a finding from my experiments, rather than a general limit on what longer training can achieve.
## What I tested
I ran these experiments while developing Purrence, across several training budgets and model revisions. I compare each result with its own control. I report cross entropy (CE) in nats per token, and use the length normalized local intelligence index where I report downstream results. These earlier experimental scores are separate from the final model's 8.4873 result.
### Residual routing
I compared LR AttnRes with learned scalar residual weights and ordinary pre norm residual addition. In a three loop run, LR AttnRes reached held out cross-entropy (CE) of 2.6239 nats per token, compared with 2.7152 for the scalar baseline and 2.7336 for pre norm. It took about 11% longer than the scalar baseline and 17% longer than pre norm. The routing queries added 768 parameters in this three loop model.
### Loop count and training length
In an approximately 1B token loop count sweep, held out CE was 2.6239 at three loops, 2.6116 at six, 2.6156 at nine, and 2.6101 at twelve. Twelve loops were marginally best at equal token count, while three processed tokens about 3.9 times faster. Over a longer horizon, the six loop run reached held out CE 2.2260 at 12B tokens versus 2.2993 for three loops. A twelve loop run reached 2.1979, but its length normalized local intelligence index was 5.758, below the six loop CE only run's 6.039. In my longest run, held out CE kept improving without sustained downstream gains. These results show that lower CE did not guarantee a higher downstream index.
### The NITP projector
I tested CE with Next Implicit Token Prediction (NITP), using a SwiGLU projection head with auxiliary weight 1. At six loops and 12B tokens, held out CE was 2.2172 with NITP versus 2.2260 with CE alone. At three loops, NITP was slightly worse: 2.3037 versus 2.2993. A six loop linear NITP projector reached 2.2320, worse than the CE only control in that comparison, so I kept the SwiGLU projector.
### NITP during cooldown
For a cooldown comparison, I restarted four continuations from the same six loop, linear-projector checkpoint at 10B tokens. Removing NITP gave the lowest held out CE at 12B, 2.2244 versus 2.2320 for the original cooldown, but its downstream index was lower, 6.029 versus 6.128. Freezing the projector barely changed CE, to 2.2322, while its index was 6.346. These older runs were evaluated in BF16, and deterministic execution settings changed between the original run and continuations. They used one seed, so I treated the downstream differences as suggestive rather than decisive and kept the later SwiGLU projector trainable.
### DeepCrossAttention
I adapted DeepCrossAttention as another way to read earlier representations. In this short, roughly 1B token test, held out CE rose from 2.5885 for the matched LR AttnRes control to 2.6230, while counted training took 32.6% longer. I used one seed and my own unfused adaptation. I dropped this version from my design, without drawing a general conclusion about the method.
### One wide block or two narrower blocks
I compared one width 384 block applied six times with two distinct width 256 blocks applied three times each, keeping six total block applications. Around 4.24B tokens, smoothed training CE was 2.2902 for one shared block and 2.3170 for two blocks. At twelve block applications the ordering reversed slightly, 2.3122 versus 2.2996 around 2.61B tokens. I did not find that one layout was universally better, though twelve applications were too slow for my budget.
### Precision and feedforward choices
In a short precision screen, moving the FFN and output projection from the tested FP8 paths to BF16 reduced held out loss from 2.5889 to 2.5013, while recorded training time changed from 297.2 to 292.2 seconds. The output projection change accounted for the largest loss difference. I also compared backbone activations at the same parameter count: fused ReLU² reached held out loss 2.5085 versus 2.5137 for SwiGLU, with SwiGLU taking 6% longer. FFN width and optimizer settings also changed to fit the budget, so I cannot attribute that result to activation alone. In three paired BF16 seeds, width 2,096 beat 2,112 on held out loss in every pair, with means of 2.5003 and 2.5064 respectively. I kept width 2,096.
### The Pulvis v2 architecture comparison
I compared the complete six loop model with a narrower Pulvis v2 shaped adaptation over the same 5B token stream. This changed several parts of the architecture at once, including block layout, attention, FFN, and context length, so it tests two architecture packages and does not isolate weight sharing. With one seed and full held out and downstream evaluation in FP32, the six loop model had lower held out CE, 2.0232 versus 2.1071, while the Pulvis shaped model had a higher length normalized index, 6.673 versus 6.172. Task scores were mixed. I read this as a comparison of the two complete configurations. I did not isolate any single component.
### Why I abandoned two pass training
I also tried a two pass latent token variant. Even with zero Jacobi iterations, it processed three times as many positions as the corresponding single pass for the same number of real training tokens. In an earlier pilot, updates with three Jacobi rounds took a median 0.955 seconds versus 0.334 seconds with zero rounds. The added work was too costly for my budget, so I abandoned the two pass run and returned to the single pass six loop model.
## My CPU benchmark results
I reran all six pinned benchmark tasks on my CPU on October 5, 2026, covering 18,928 examples in about 8.9 minutes. I used FP32 math, zero-shot prompts and the full vocabulary, with autocast and TF32 disabled.
I obtained a **normalized Intelligence Index of 8.4873**. My unrounded result was `8.487306383044526`, and my raw-accuracy index was `6.997659441758839`.
| Benchmark | Examples I evaluated | My accuracy | My normalized accuracy ||---|---:|---:|---:|| ARC Easy | 2,376 | 34.18% | 34.55% || ARC Challenge | 1,172 | 20.39% | 23.63% || HellaSwag | 10,042 | 27.50% | 27.81% || PIQA | 1,838 | 55.33% | 56.64% || ArithMark 3 | 1,000 | 34.80% | 34.80% || ArithMark 2 | 2,500 | 26.44% | 25.92% |
I independently recalculated the predictions, accuracies and both index variants from the saved per-example outputs. I reproduced every task accuracy and normalized accuracy from my original native evaluation. I use ArithMark 3 in the index and report ArithMark 2 separately.
I used the pinned local evaluation protocol with harness revision `d6de81643928d653435c431bae19945d41d32520`. I am reporting local measurements and have not obtained independent leaderboard verification. I selected this checkpoint through repeated benchmark evaluations.
## Reproducing the evaluation
I reproduce the five tasks used in my index with the zero shot protocol in `evaluation_config.json`: ARC Easy, ARC Challenge, HellaSwag, PIQA, and the official ArithMark 3 evaluation. I use CPU FP32 continuation scoring without a chat template. I pin the task datasets and evaluator revisions, check hashes for the weights, configuration, tokenizer and model code, and independently recalculate both accuracy measures from the saved predictions.
I use Python 3.11. From the downloaded model directory, I install the evaluation dependencies and run:
```bashpython -m pip install -r requirements-eval.txtpython reproduce_evaluation.py --model . --output results```
I use an empty or new output directory. For a Hub copy, I sign in with `hf auth login` if access requires it, then run:
```bashpython reproduce_evaluation.py --model Jonnester/Purrence-3M --output results```
I record the resolved Hub commit automatically. I can also pass `--revision COMMIT_SHA` to select a particular snapshot. I require the same verified model file hashes in either case.
I save full per example outputs in `results/lm_eval_results.json` and `results/arithmark3/`. In `results/reaggregation.json`, I record the model and evaluator hashes, dataset revisions, settings, example counts, recalculated metrics and index. My complete CPU reproduction covered 16,428 examples and returned `8.487306383044526`. I report ArithMark 2 separately from my earlier six task run.
## How I run it
I use Python 3.11 and install the pinned dependencies from the repository directory:
```bashpython -m pip install -r requirements.txtpython load_model.py --prompt "Once upon a time" --max-new-tokens 32```
I use CPU inference and greedy generation by default. I load the Safetensors weights with strict parameter checks and verify the tokenizer hash. I also check for nonfinite weights and an unexpected parameter count.
I can generate text or score continuations through the Python API:
```pythonfrom load_model import load_modelfrom purrence_runtime.scorer import Scorer
model, tokenizer = load_model()scorer = Scorer(model, tokenizer)print(scorer.generate("Once upon a time", max_new_tokens=32))print(scorer.score([(tokenizer.encode("The sky is"), tokenizer.encode(" blue."))]))```
## How I use Transformers
I use the same weights and tokenizer through the Transformers Auto classes. I enable `trust_remote_code` because I include the inference implementation for my custom architecture. I use FP32 and do not use a KV cache.
```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
repo = "Jonnester/Purrence-3M"# I can set revision to a commit hash to pin this snapshot.tokenizer = AutoTokenizer.from_pretrained(repo, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained( repo, trust_remote_code=True, torch_dtype=torch.float32).eval()inputs = tokenizer("Once upon a time", return_tensors="pt")with torch.no_grad(): output = model.generate(**inputs, max_new_tokens=32, do_sample=False, use_cache=False)print(tokenizer.decode(output[0], skip_special_tokens=True))```
I preserve the original tokenizer behavior: literal `<|endoftext|>` in a prompt is ordinary text. I reserve token ID 2047 for structural boundaries, end of generation and padding.
## My generation example
I ran the command above on my CPU with the prompt `Once upon a time` and a limit of 32 new tokens. I received this exact, unedited continuation:
```text, had a far apartment border. The border was 100 million years older than the next```
I show only the generated continuation because that is what the command prints. I reached the token limit before completing the sentence.
## My license
I have not selected a release license yet. I include the third-party license notices for their respective source components. I do not present those notices as a license for my model weights or the entire package.123456789101112131415161718192021222324252627{ "vocab_size": 2048, "width": 384, "heads": 6, "mlp_width": 2096, "loops": 6, "rank": 128, "controller_width": 16, "max_seq_len": 8192, "norm_eps": 1e-06, "routing_eps": 1.1920928955078125e-07, "model_type": "purrence", "architectures": [ "PurrenceForCausalLM" ], "torch_dtype": "float32", "bos_token_id": 2047, "eos_token_id": 2047, "pad_token_id": 2047, "tie_word_embeddings": true, "use_cache": false, "max_position_embeddings": 8192, "auto_map": { "AutoConfig": "configuration_purrence.PurrenceConfig", "AutoModelForCausalLM": "modeling_purrence.PurrenceForCausalLM" }}1234567891011121314151617181920212223"""Configuration for the fixed Purrence-3M inference architecture."""from dataclasses import asdictfrom transformers import PretrainedConfigfrom .purrence_core import ModelConfig
class PurrenceConfig(PretrainedConfig): model_type = "purrence"
def __init__(self, **kwargs): dimensions = asdict(ModelConfig()) for name, default in dimensions.items(): dimensions[name] = kwargs.pop(name, default) ModelConfig(**dimensions).validate() kwargs.setdefault("bos_token_id", 2047) kwargs.setdefault("eos_token_id", 2047) kwargs.setdefault("pad_token_id", 2047) kwargs.setdefault("tie_word_embeddings", True) super().__init__(**kwargs) for name, value in dimensions.items(): setattr(self, name, value) self.max_position_embeddings = self.max_seq_len self.use_cache = False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131{ "schema_version": 1, "protocol": "local-pinned-open-slm-zero-shot-v2", "harness": { "distribution": "lm_eval", "repository": "https://github.com/EleutherAI/lm-evaluation-harness", "revision": "d6de81643928d653435c431bae19945d41d32520", "python_requires": ">=3.10", "task_configs": { "arc_easy": "lm_eval/tasks/arc/arc_easy.yaml", "arc_challenge": "lm_eval/tasks/arc/arc_challenge.yaml", "hellaswag": "lm_eval/tasks/hellaswag/hellaswag.yaml", "piqa": "lm_eval/tasks/piqa/piqa.yaml" } }, "arithmark3": { "repository": "AxiomicLabs/Arithmark-3.0", "revision": "6f6e59dd9b7e2c63455f7af7f838f9ecc3d0a746", "script": "bencharithmark-3.py", "dataset": "arithmark-3.jsonl", "examples": 1000, "script_sha256": "09667e1ea05ecd8b91dbfea14a47365b555c72622afed9fc284c127ecd5e1bcd" }, "model": { "default_repo": "Jonnester/Purrence-3M", "device": "cpu", "dtype": "float32", "trust_remote_code": true, "batch_size": 16, "max_length": 8192, "add_bos_token": false, "default_local_path": ".", "expected_weights_sha256": "9c9f8d29004ce3563090de3c9be42059c5e2f928e053d4b17637f2215d7972ec", "expected_file_sha256": { "config.json": "a82f737624152185ff9afd9573a2d82e3592fcd3f61df9dbdac25188e25c659e", "modeling_purrence.py": "6467854a7a53185b2ed2693cf0f9d0150898a13efb35cf0c12cd3b53691ca817", "configuration_purrence.py": "a33340909d58f0505262f5111ed41da0faa4222ee99a439cd93c700c3c9c30ee", "tokenization_purrence.py": "c25e6e0e712e754e2f6d09a45899f84a90a611a7b32ac43515b9cd09c075dfec", "purrence_core.py": "0141fff6cc77cc590145873fa754a6fec1aeec67cc19be4d8a9dce769728c02b", "tokenizer_config.json": "69bfe2ccb62a039a97e6df0ca4a670440170eae950aa735760cbf0e95db962e5", "tokenizer/ordinary-tokenizer.json": "fc240b741112488b639a711f502305601e3b8a1b01c5ae93a48b9ae55692dd33", "tokenizer/artifact.json": "4c2241f6f7deffc43043ae1e91eea87434de6725bf0c4e5d2dfe5a45588733bd" } }, "evaluation": { "precision": "fp32", "num_fewshot": 0, "limit": null, "apply_chat_template": false, "system_instruction": null, "log_samples": true, "seeds": { "random": 17, "numpy": 17, "torch": 17, "fewshot": 17 }, "bootstrap_iters": 1000, "metrics": [ "acc", "acc_norm" ] }, "tasks": { "arc_easy": { "task_version": 1.0, "dataset_path": "allenai/ai2_arc", "dataset_name": "ARC-Easy", "storage_adapter": { "dataset_name": null, "data_dir": "ARC-Easy" }, "dataset_revision": "54cd56ea77687f84868e2cb8d58e3f462bdd0d45", "evaluation_split": "test", "examples": 2376, "chance": 0.25, "metrics": [ "acc", "acc_norm" ] }, "arc_challenge": { "task_version": 1.0, "dataset_path": "allenai/ai2_arc", "dataset_name": "ARC-Challenge", "storage_adapter": { "dataset_name": null, "data_dir": "ARC-Challenge" }, "dataset_revision": "54cd56ea77687f84868e2cb8d58e3f462bdd0d45", "evaluation_split": "test", "examples": 1172, "chance": 0.25, "metrics": [ "acc", "acc_norm" ] }, "hellaswag": { "task_version": 1.0, "dataset_path": "Rowan/hellaswag", "dataset_name": null, "dataset_revision": "218ec52e09a7e7462a5400043bb9a69a41d06b76", "evaluation_split": "validation", "examples": 10042, "chance": 0.25, "metrics": [ "acc", "acc_norm" ] }, "piqa": { "task_version": 1.0, "dataset_path": "baber/piqa", "dataset_name": null, "dataset_revision": "142f6d7367fd9877f0fb3b5734ea6a545f54cdd1", "evaluation_split": "validation", "examples": 1838, "chance": 0.5, "metrics": [ "acc", "acc_norm" ] } }, "index": { "normalized_formula": "100 * (((hellaswag.acc_norm - 0.25) / 0.75) + ((mean(arc_easy.acc_norm, arc_challenge.acc_norm) - 0.25) / 0.75) + ((piqa.acc_norm - 0.5) / 0.5) + 0.65 * ((arithmark3.acc_norm - 0.25) / 0.75)) / 3.65", "raw_formula": "100 * (((hellaswag.acc - 0.25) / 0.75) + ((mean(arc_easy.acc, arc_challenge.acc) - 0.25) / 0.75) + ((piqa.acc - 0.5) / 0.5) + 0.65 * ((arithmark3.acc_norm - 0.25) / 0.75)) / 3.65", "note": "Leaderboard formula applied to these local measurements; independent leaderboard verification is not implied." }}123456789101112131415161718192021MIT License
Copyright (c) 2025 Jonnester
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12345678910111213141516171819202122232425262728293031323334353637"""Load the inference-only FP32 Purrence package without training state."""import argparseimport jsonfrom pathlib import Pathfrom dataclasses import fieldsimport torchfrom safetensors.torch import load_filefrom purrence_runtime.config import ModelConfigfrom purrence_runtime.model import RecurrentLMfrom purrence_runtime.tokenizer import Sub3MTokenizerfrom purrence_runtime.scorer import Scorer
def load_model(directory=None, device="cpu"): root = Path(directory) if directory else Path(__file__).resolve().parent values = json.loads((root / "config.json").read_text()) config = ModelConfig(**{f.name: values[f.name] for f in fields(ModelConfig)}) model = RecurrentLM(config) state = load_file(str(root / "model.safetensors"), device="cpu") model.load_state_dict(state, strict=True) if any(not torch.isfinite(p).all() for p in model.parameters()): raise ValueError("Nonfinite model weights") if model.parameter_count() != 2987712: raise ValueError("Inference parameter count differs from the qualified model") model = model.to(device).float().eval() tokenizer = Sub3MTokenizer(root / "tokenizer") return model, tokenizer
if __name__ == "__main__": p = argparse.ArgumentParser() p.add_argument("--directory", type=Path) p.add_argument("--device", default="cpu") p.add_argument("--prompt", default="Once upon a time") p.add_argument("--max-new-tokens", type=int, default=32) args = p.parse_args() torch.set_num_threads(2) model, tokenizer = load_model(args.directory, args.device) print(Scorer(model, tokenizer).generate(args.prompt, max_new_tokens=args.max_new_tokens))123456789101112131415161718192021MIT License
Copyright (c) 2024 Keller Jordan
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123version https://git-lfs.github.com/spec/v1oid sha256:9c9f8d29004ce3563090de3c9be42059c5e2f928e053d4b17637f2215d7972ecsize 119517281234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Transformers inference adapter using the unchanged native model equations."""from dataclasses import fieldsimport torchfrom transformers import PreTrainedModel, GenerationMixinfrom transformers.modeling_outputs import CausalLMOutputfrom .configuration_purrence import PurrenceConfigfrom .purrence_core import ModelConfig, RecurrentLM
class PurrenceForCausalLM(PreTrainedModel, GenerationMixin): config_class = PurrenceConfig base_model_prefix = "" main_input_name = "input_ids" _supports_cache_class = False
def __init__(self, config, dtype=None): super().__init__(config) native = RecurrentLM(ModelConfig(**{ f.name: getattr(config, f.name) for f in fields(ModelConfig) })) self.embedding = native.embedding self.block = native.block self.queries = native.queries
def get_input_embeddings(self): return self.embedding
def set_input_embeddings(self, value): self.embedding = value
def get_output_embeddings(self): return None # The native forward uses the embedding weight directly.
def read(self, sources, query): return RecurrentLM.read(self, sources, query)
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs): return dict(input_ids=input_ids, attention_mask=attention_mask, use_cache=False)
def forward(self, input_ids=None, attention_mask=None, return_dict=None, use_cache=False, past_key_values=None, labels=None, **kwargs): if labels is not None or past_key_values is not None: raise ValueError("This inference adapter does not implement training or a KV cache") if input_ids is None or input_ids.ndim != 2 or input_ids.numel() == 0: raise ValueError("Expected a nonempty batch of token IDs") if attention_mask is None: mask = torch.ones_like(input_ids, dtype=torch.bool) else: if attention_mask.shape != input_ids.shape: raise ValueError("Attention mask shape differs from input IDs") mask = attention_mask.bool() lengths = mask.sum(-1) if (lengths == 0).any() or (lengths > self.config.max_seq_len).any(): raise ValueError("Each sequence must contain 1 to 8192 unmasked tokens") packed = input_ids[mask] starts = torch.cat((lengths.new_zeros(1), lengths.cumsum(0)[:-1])) document_starts = packed.eq(self.config.eos_token_id) document_starts[starts] = True offsets = document_starts.nonzero().flatten() cu = torch.cat((offsets, offsets.new_tensor([packed.numel()]))).to(torch.int32) positions = torch.arange(packed.numel(), device=packed.device) - torch.repeat_interleave(offsets, cu.diff().long()) with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH): values = RecurrentLM.forward(self, packed, cu, positions) logits = values.new_zeros((*input_ids.shape, self.config.vocab_size)) logits[mask] = values if return_dict is False or (return_dict is None and not self.config.use_return_dict): return (logits,) return CausalLMOutput(logits=logits)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""Architecture dimensions of the fixed inference export."""from dataclasses import dataclass
@dataclass(frozen=True)class ModelConfig: vocab_size: int = 2048 width: int = 384 heads: int = 6 mlp_width: int = 2096 loops: int = 6 rank: int = 128 controller_width: int = 16 max_seq_len: int = 8192 norm_eps: float = 1e-06 routing_eps: float = 1.1920928955078125e-07
def validate(self): if self != ModelConfig(): raise ValueError("This runtime supports the released Purrence architecture only")
"""Six-loop Attention Residuals inference with per-head XSA and gates."""import torchfrom torch import nnimport torch.nn.functional as F
def rms(x, eps): work = x if x.dtype == torch.float64 else x.float() return (work * torch.rsqrt(work.square().mean(-1, keepdim=True) + eps)).to(x.dtype)
def depth_read(sources, query, eps=2 ** -23): values = torch.stack(sources) work = values if values.dtype == torch.float64 else values.float() inverse_rms = torch.rsqrt(work.square().mean(-1) + eps) scores = (work[..., -query.numel():] * query.to(work.dtype)).sum(-1) * inverse_rms weights = scores.softmax(dim=0) return (weights[..., None] * work).sum(0).to(values.dtype)
def document_layout(ids, boundary_id): flat = ids.reshape(-1) starts = flat.eq(boundary_id) starts[0] = True if ids.ndim == 2: starts[::ids.shape[1]] = True offsets = starts.nonzero().flatten() cu = torch.cat((offsets, offsets.new_tensor([flat.numel()]))).to(torch.int32) positions = torch.arange(flat.numel(), device=ids.device) - torch.repeat_interleave(offsets, cu.diff().long()) return cu, positions
def half_rope(x, positions, frequencies, factors=None): rotary_dim = x.shape[-1] // 2 if factors is None: angle = positions.float()[:, None] * frequencies[None] cosine, sine = angle.cos().to(x.dtype)[:, None], angle.sin().to(x.dtype)[:, None] else: cosine, sine = (factor.to(x.dtype) for factor in factors) even, odd = x[..., :rotary_dim:2], x[..., 1:rotary_dim:2] rotated = torch.stack((even * cosine + odd * sine, odd * cosine - even * sine), dim=-1) return torch.cat((rotated.flatten(-2), x[..., rotary_dim:]), dim=-1)
def offset_keys(keys, positions): rotary_dim = keys.shape[-1] // 2 previous = torch.cat((keys[:1, :, rotary_dim:], keys[:-1, :, rotary_dim:])) stationary = torch.where(positions[:, None, None] > 0, previous, keys[..., rotary_dim:]) return torch.cat((keys[..., :rotary_dim], stationary), dim=-1)
def attention(q, k, v, cu): result = [] boundaries = cu.tolist() for start, end in zip(boundaries, boundaries[1:]): query, key, value = (item[start:end].transpose(0, 1)[None] for item in (q, k, v)) out = F.scaled_dot_product_attention(query, key, value, is_causal=True) result.append(out[0].transpose(0, 1)) return torch.cat(result)
class SharedBlock(nn.Module): def __init__(self, config): super().__init__() self.config = config self.q = nn.Linear(config.width, config.width, bias=False) self.k = nn.Linear(config.width, config.width, bias=False) self.v = nn.Linear(config.width, config.width, bias=False) self.o = nn.Linear(config.width, config.width, bias=False) self.up = nn.Linear(config.width, config.mlp_width, bias=False) self.down = nn.Linear(config.mlp_width, config.width, bias=False) self.xsa = nn.Linear(config.controller_width, config.heads, bias=False) self.gate = nn.Linear(config.controller_width, config.heads, bias=False) head_dim = config.width // config.heads self.register_buffer("frequencies", (1 / 1024) ** torch.linspace(0, 1, head_dim // 4), persistent=False)
def rotary_factors(self, positions, dtype): angle = positions.float()[:, None] * self.frequencies[None] return angle.cos().to(dtype)[:, None], angle.sin().to(dtype)[:, None]
def attend(self, x, cu, positions, rope_factors): config = self.config q, k, v = [F.linear(x, getattr(self, name).weight.to(x.dtype)).view( -1, config.heads, config.width // config.heads) for name in ('q', 'k', 'v')] q = half_rope(rms(q, config.routing_eps), positions, self.frequencies, rope_factors) k = half_rope(rms(k, config.routing_eps), positions, self.frequencies, rope_factors) k = offset_keys(k, positions) y = attention(q, k, v, cu) local = x[..., :config.controller_width] alpha, gate = self.xsa(local), self.gate(local) dot = (y * v).sum(-1, keepdim=True) denominator = v.square().sum(-1, keepdim=True).clamp_min(1e-8) y = y - alpha.tanh().to(y.dtype)[..., None] * (dot / denominator) * v y = y * gate.sigmoid().to(y.dtype)[..., None] return F.linear(y.contiguous().flatten(-2), self.o.weight.to(y.dtype))
def mlp(self, x): return self.down(self.up(x).relu().square())
class RecurrentLM(nn.Module): def __init__(self, config=None): super().__init__() self.config = config or ModelConfig() self.config.validate() self.embedding = nn.Embedding(self.config.vocab_size, self.config.width) self.block = SharedBlock(self.config) self.queries = nn.Parameter(torch.zeros(2 * self.config.loops, self.config.rank))
def read(self, sources, query): x = sources[0] if query is None else depth_read(sources, query, self.config.routing_eps) return rms(x, self.config.norm_eps)
def forward(self, ids, cu_seqlens=None, positions=None): if ids.ndim not in (1, 2) or ids.numel() == 0: raise ValueError("Expected nonempty one- or two-dimensional token IDs") if cu_seqlens is None: cu_seqlens, positions = document_layout(ids, self.config.vocab_size - 1) if positions is None: raise ValueError("Explicit packed boundaries require explicit document positions") if int(cu_seqlens.diff().max()) > self.config.max_seq_len: raise ValueError("Document segment exceeds max_seq_len") embedding = self.embedding(ids.reshape(-1)) rope_factors = self.block.rotary_factors(positions, embedding.dtype) sources = [embedding] for loop in range(self.config.loops): x = self.read(sources, None if loop == 0 else self.queries[2 * loop - 1]) a = self.block.attend(x, cu_seqlens, positions, rope_factors) x = self.read(sources + [a], self.queries[2 * loop]) m = self.block.mlp(x) sources.append(a + m) x = self.read(sources, self.queries[-1]) return F.linear(x, self.embedding.weight).view(*ids.shape, self.config.vocab_size)
def parameter_count(self): return sum(parameter.numel() for parameter in self.parameters())
#!/usr/bin/env python3"""Small runtime for the reviewed 2048-ID tokenizer and structural boundaries."""import hashlibimport jsonfrom pathlib import Path
class Sub3MTokenizer: vocab_size = 2048 boundary_id = 2047
def __init__(self, artifact_dir): import tokenizers directory = Path(artifact_dir) metadata = json.loads((directory / "artifact.json").read_text(encoding="utf-8")) if tokenizers.__version__ != metadata["tokenizers_version"]: raise RuntimeError("Use tokenizers==" + metadata["tokenizers_version"]) path = directory / "ordinary-tokenizer.json" if hashlib.sha256(path.read_bytes()).hexdigest() != metadata["tokenizer_sha256"]: raise ValueError("Tokenizer file does not match its artifact hash") self.backend = tokenizers.Tokenizer.from_file(str(path)) if self.backend.get_vocab_size() != 2047 or metadata["vocab_size"] != 2048: raise ValueError("Expected 2047 ordinary IDs and one structural boundary") if json.loads(path.read_text(encoding="utf-8")).get("added_tokens"): raise ValueError("Ordinary encoder must not recognize structural token spellings") self.metadata = metadata
def encode(self, text): """Encode literal text; even '<|endoftext|>' remains ordinary content.""" if not isinstance(text, str): raise TypeError("encode expects a Unicode string") ids = self.backend.encode(text, add_special_tokens=False).ids if any(token_id >= self.boundary_id for token_id in ids): raise ValueError("Ordinary encoding emitted a reserved ID") return ids
def decode(self, ids, skip_boundaries=False): """Decode generated IDs; optionally omit structural boundary markers.
Arbitrary generated byte sequences can be invalid UTF-8; the ByteLevel decoder replaces invalid sequences. Every encoded valid string roundtrips. """ chunks = [] ordinary = [] for token_id in ids: if type(token_id) is not int or token_id not in range(self.vocab_size): raise ValueError("Token ID must be an integer in [0, 2048)") if token_id == self.boundary_id: chunks.append(self.backend.decode(ordinary, skip_special_tokens=False)) ordinary = [] if not skip_boundaries: chunks.append(self.metadata["boundary_special"]["spelling"]) else: ordinary.append(token_id) chunks.append(self.backend.decode(ordinary, skip_special_tokens=False)) return "".join(chunks)1"""FP32 inference for the released Purrence model."""1from purrence_core import ModelConfig1from purrence_core import RecurrentLM123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117from contextlib import contextmanagerimport torchimport torch.nn.functional as Ffrom .tokenizer import Sub3MTokenizerfrom pathlib import PathTOKENIZER = Path(__file__).resolve().parents[1] / "tokenizer"def cross_entropy_sum(logits, targets): return F.cross_entropy(logits.float(), targets, reduction="sum")
@contextmanagerdef fp32_math(device): """Full FP32 inference, including attention, without leaking backend flags.""" from torch.nn.attention import SDPBackend, sdpa_kernel previous_precision = torch.get_float32_matmul_precision() previous_tf32 = torch.backends.cuda.matmul.allow_tf32 previous_cudnn_tf32 = torch.backends.cudnn.allow_tf32 try: torch.set_float32_matmul_precision("highest") torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False with torch.autocast(device.type, enabled=False), sdpa_kernel(SDPBackend.MATH): yield finally: torch.set_float32_matmul_precision(previous_precision) torch.backends.cuda.matmul.allow_tf32 = previous_tf32 torch.backends.cudnn.allow_tf32 = previous_cudnn_tf32
class Scorer: def __init__(self, model, tokenizer=None, batch_size=16): if batch_size < 1: raise ValueError("Batch size must be positive") self.model = model.eval() self.tokenizer = tokenizer or Sub3MTokenizer(TOKENIZER) self.batch_size = batch_size self.device = next(model.parameters()).device if any(p.is_floating_point() and p.dtype != torch.float32 for p in model.parameters()): raise ValueError("This scorer requires FP32 inference weights")
def inference_context(self): return fp32_math(self.device)
@torch.no_grad() def score(self, requests, max_length=None): limit = max_length or self.model.config.max_seq_len if not 1 <= limit <= self.model.config.max_seq_len: raise ValueError("Scoring context is outside the model's context limit") results = [] for begin in range(0, len(requests), self.batch_size): inputs, targets, lengths, counts = [], [], [], [] for context, continuation in requests[begin:begin + self.batch_size]: if not continuation or len(continuation) > limit: raise ValueError("Continuation must contain between one and max_length tokens") context = context or [self.tokenizer.boundary_id] sequence = (list(context) + list(continuation))[-(limit + 1):] inputs.extend(sequence[:-1]) targets.append(continuation) lengths.append(len(sequence) - 1) counts.append(len(continuation)) ids = torch.tensor(inputs, dtype=torch.long, device=self.device) cu = F.pad(torch.tensor(lengths, device=self.device).cumsum(0), (1, 0)).to(torch.int32) positions = torch.cat([torch.arange(length, device=self.device) for length in lengths]) with self.inference_context(): logits = self.model(ids, cu, positions) offset = 0 for length, count, target in zip(lengths, counts, targets): selected = logits[offset + length - count:offset + length].float() target = torch.tensor(target, device=self.device) value = -cross_entropy_sum(selected, target) greedy = selected.argmax(-1).eq(target).all() results.append((float(value), bool(greedy))) offset += length return results
def rolling(self, text): tokens = self.tokenizer.encode(text) limit = self.model.config.max_seq_len requests = [] for start in range(0, len(tokens), limit): continuation = tokens[start:start + limit] if not start: context = [self.tokenizer.boundary_id] elif len(continuation) < limit: # LM-Eval's final partial window keeps enough preceding tokens # to use the full model context; full-sized windows keep one. context_size = limit - len(continuation) + 1 context = tokens[start - context_size:start] else: context = [tokens[start - 1]] requests.append((context, continuation)) return sum(score for score, _ in self.score(requests))
@torch.no_grad() def generate(self, prompt, max_new_tokens=128, temperature=0.0, until=(), seed=17): if max_new_tokens < 0 or temperature < 0: raise ValueError("Generation length and temperature must be nonnegative") if isinstance(until, str): until = [until] if any(not stop for stop in until): raise ValueError("Stop strings must be nonempty") prefix = self.tokenizer.encode(prompt) or [self.tokenizer.boundary_id] generated = [] rng = torch.Generator(device=self.device).manual_seed(seed) for _ in range(max_new_tokens): ids = torch.tensor((prefix + generated)[-self.model.config.max_seq_len:], device=self.device) with self.inference_context(): logits = self.model(ids)[-1].float() token = int(logits.argmax()) if temperature == 0 else int(torch.multinomial( (logits / temperature).softmax(-1), 1, generator=rng)) if token == self.tokenizer.boundary_id: break generated.append(token) text = self.tokenizer.decode(generated) endings = [text.index(stop) for stop in until if stop in text] if endings: return text[:min(endings)] return self.tokenizer.decode(generated)1from purrence_core import Sub3MTokenizer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292#!/usr/bin/env python3"""Reproduce Purrence's documented five-task CPU FP32 evaluation."""import argparseimport hashlibimport jsonimport mathimport osimport platformimport runpyimport sysimport timefrom pathlib import Path
ROOT = Path(__file__).resolve().parentCONFIG_PATH = ROOT / "evaluation_config.json"
def read_config(): raw = CONFIG_PATH.read_bytes() return json.loads(raw), hashlib.sha256(raw).hexdigest()
def verify_model_files(model_path, config): actual = {} for filename, expected in config["model"]["expected_file_sha256"].items(): path = model_path / filename if not path.is_file(): raise RuntimeError("Model snapshot lacks required file: " + filename) digest = hashlib.sha256(path.read_bytes()).hexdigest() if digest != expected: raise RuntimeError("Model source file SHA-256 mismatch: " + filename) actual[filename] = digest weights_sha = hashlib.sha256((model_path / "model.safetensors").read_bytes()).hexdigest() if weights_sha != config["model"]["expected_weights_sha256"]: raise RuntimeError("Weights SHA-256 differs from the documented inference snapshot") actual["model.safetensors"] = weights_sha return actual
def task_loader_overrides(task): kwargs = {"revision": task["dataset_revision"]} storage = task.get("storage_adapter") if storage: if (set(storage) != {"dataset_name", "data_dir"} or storage["dataset_name"] is not None or storage["data_dir"] != task["dataset_name"]): raise ValueError("Invalid ARC storage adapter") return {"dataset_name": None}, {**kwargs, "data_dir": storage["data_dir"]} return {}, kwargs
def build_group(config): members = [] for name, task in config["tasks"].items(): overrides, dataset_kwargs = task_loader_overrides(task) member = {"task": name, "dataset_kwargs": dataset_kwargs} member.update(overrides) members.append(member) return {"group": "purrence_pinned_evaluation", "task": members}
def verify_harness(config): import importlib.metadata from pathlib import Path dist = importlib.metadata.distribution("lm_eval") direct = json.loads(dist.read_text("direct_url.json") or "{}") expected = config["harness"]["revision"] if direct.get("vcs_info", {}).get("commit_id") != expected: raise RuntimeError("lm_eval is not installed from the pinned source revision") url = direct.get("url", "").removesuffix(".git") if url != config["harness"]["repository"]: raise RuntimeError("lm_eval source repository does not match the pinned config") sources = {} for name, relative in config["harness"]["task_configs"].items(): path = Path(dist.locate_file(relative)) if not path.is_file(): raise RuntimeError("Missing pinned task source: " + relative) sources[name] = hashlib.sha256(path.read_bytes()).hexdigest() return {"version": dist.version, "revision": expected, "repository": url, "task_source_sha256": sources}
def load_tasks(config): from lm_eval.tasks import TaskManager manager = TaskManager() tasks = manager.load(build_group(config))["tasks"] for name, expected in config["tasks"].items(): task = tasks[name] overrides, kwargs = task_loader_overrides(expected) if task.get_config("dataset_path") != expected["dataset_path"]: raise RuntimeError("Unexpected dataset path for " + name) expected_name = overrides.get("dataset_name", expected["dataset_name"]) if task.get_config("dataset_name") != expected_name or task.get_config("dataset_kwargs") != kwargs: raise RuntimeError("Dataset revision/config override failed for " + name) if task.VERSION != expected["task_version"] or task.OUTPUT_TYPE != "multiple_choice": raise RuntimeError("Unexpected task version or output type for " + name) if not set(expected["metrics"]).issubset(task.aggregation()): raise RuntimeError("Required metrics are unavailable for " + name) split = task.get_config("test_split") or task.get_config("validation_split") if split != expected["evaluation_split"] or len(task.eval_docs) != expected["examples"]: raise RuntimeError("Evaluation split/count mismatch for " + name) return manager, tasks
def check_samples(results, config): for name, task in config["tasks"].items(): samples = results.get("samples", {}).get(name, []) counts = results.get("n-samples", {}).get(name, {}) n = task["examples"] if counts.get("original") != n or counts.get("effective") != n or len(samples) != n: raise RuntimeError("Full per-example output missing for " + name) for sample in samples: args = sample.get("arguments", []) if not args or any(len(arg) != 2 or not all(isinstance(x, str) for x in arg) for arg in args): raise RuntimeError("Rendered choice prompts missing for " + name) if len(sample.get("resps", [])) != len(args) or len(sample.get("filtered_resps", [])) != len(args): raise RuntimeError("Per-choice model outputs missing for " + name) if not {"acc", "acc_norm"}.issubset(sample.get("metrics", [])): raise RuntimeError("Per-example metrics missing for " + name)
def json_default(value): if hasattr(value, "tolist"): return value.tolist() return str(value)
def reaggregate(results, arith, config): summary = {} for name, task in config["tasks"].items(): samples = results["samples"][name] seen = set() correct = {"acc": 0, "acc_norm": 0} for sample in samples: doc_id = sample["doc_id"] if doc_id in seen: raise RuntimeError("Duplicate doc_id in " + name) seen.add(doc_id) responses = [float(item[0]) for item in sample["filtered_resps"]] if not responses or not all(math.isfinite(x) for x in responses): raise RuntimeError("Invalid choice scores in " + name) choices = (sample["doc"]["choices"]["text"] if name.startswith("arc_") else sample["doc"]["choices"] if name == "hellaswag" else [sample["doc"]["sol1"], sample["doc"]["sol2"]]) if len(choices) != len(responses) or any(sample["arguments"][i][1] != " " + choice for i, choice in enumerate(choices)): raise RuntimeError("Choice prompts do not match the task document in " + name) target = int(sample["target"]) for metric, scores in (("acc", responses), ("acc_norm", [x / len(c) for x, c in zip(responses, choices)])): prediction = max(range(len(scores)), key=scores.__getitem__) if prediction == target: correct[metric] += 1 if int(sample[metric]) != int(prediction == target): raise RuntimeError("Logged per-example correctness mismatch in " + name) summary[name] = {"examples": len(samples), **{m: c / len(samples) for m, c in correct.items()}} for metric in correct: if abs(summary[name][metric] - results["results"][name][metric + ",none"]) > 1e-12: raise RuntimeError("Reaggregated metric differs from lm_eval in " + name)
rows = arith["results"]["arithmark-3"]["predictions"] if len(rows) != config["arithmark3"]["examples"]: raise RuntimeError("ArithMark did not preserve every prediction") for metric, pred_key, score_key in (("acc", "raw_prediction", "raw_scores"), ("acc_norm", "normalized_prediction", "normalized_scores")): if not all(all(math.isfinite(float(v)) for v in row[score_key]) for row in rows): raise RuntimeError("ArithMark contains non-finite scores") if not all(max(range(len(row[score_key])), key=row[score_key].__getitem__) == row[pred_key] for row in rows): raise RuntimeError("ArithMark saved prediction differs from scores") count = len(rows) summary["arithmark3"] = {"examples": count, "acc": sum(row["raw_prediction"] == row["label"] for row in rows) / count, "acc_norm": sum(row["normalized_prediction"] == row["label"] for row in rows) / count} for metric in ("acc", "acc_norm"): if abs(summary["arithmark3"][metric] - arith["results"]["arithmark-3"][metric] / 100) > 1e-12: raise RuntimeError("ArithMark reaggregation differs from official script")
indices = {} for metric in ("acc", "acc_norm"): arc = (summary["arc_easy"][metric] + summary["arc_challenge"][metric]) / 2 indices[metric] = 100 * (((summary["hellaswag"][metric] - .25) / .75) + ((arc - .25) / .75) + ((summary["piqa"][metric] - .5) / .5) + .65 * ((summary["arithmark3"]["acc_norm"] - .25) / .75)) / 3.65 return {"metrics": summary, "intelligence_index": indices, "examples_total": sum(item["examples"] for item in summary.values())}
def main(): config, config_sha = read_config() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model", default=config["model"]["default_local_path"], help="Local model directory or Hugging Face model ID (default: current directory)") parser.add_argument("--output", type=Path, required=True, help="Directory for full per-example results and reaggregation") parser.add_argument("--revision", default=None, help="Hub model revision; defaults to the current main revision") args = parser.parse_args() if sys.version_info < (3, 10): raise SystemExit("Python 3.10 or newer is required") if args.output.exists() and any(args.output.iterdir()): raise SystemExit("Output directory must be empty or absent: " + str(args.output)) args.output.mkdir(parents=True, exist_ok=True)
os.environ.setdefault("HF_DATASETS_CACHE", str(args.output / "hf-cache" / "datasets")) os.environ.setdefault("HF_HUB_CACHE", str(args.output / "hf-cache" / "hub")) os.environ["TOKENIZERS_PARALLELISM"] = "false" os.environ.setdefault("OMP_NUM_THREADS", "4")
import torch from huggingface_hub import hf_hub_download, snapshot_download from lm_eval import simple_evaluate from lm_eval.models.huggingface import HFLM
torch.set_num_threads(min(4, torch.get_num_threads())) torch.set_float32_matmul_precision("highest") torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False started = time.monotonic()
model_arg = Path(args.model).expanduser() if model_arg.is_dir(): model_path = model_arg.resolve() model_source = {"kind": "local", "path": str(model_path)} else: model_path = Path(snapshot_download(args.model, revision=args.revision)) model_revision = model_path.name model_source = {"kind": "huggingface_hub", "repo_id": args.model, "revision": model_revision} model_files = verify_model_files(model_path, config) weights_sha = model_files["model.safetensors"]
harness = verify_harness(config) manager, tasks = load_tasks(config) cfg = config["model"] lm = HFLM(pretrained=str(model_path), device=cfg["device"], dtype=cfg["dtype"], trust_remote_code=cfg["trust_remote_code"], batch_size=cfg["batch_size"], max_length=cfg["max_length"], add_bos_token=cfg["add_bos_token"]) result = simple_evaluate(model=lm, tasks=list(tasks.values()), task_manager=manager, num_fewshot=config["evaluation"]["num_fewshot"], batch_size=cfg["batch_size"], log_samples=config["evaluation"]["log_samples"], apply_chat_template=False, system_instruction=None, limit=None, random_seed=17, numpy_random_seed=17, torch_random_seed=17, fewshot_random_seed=17, bootstrap_iters=1000) check_samples(result, config) (args.output / "lm_eval_results.json").write_text( json.dumps(result, indent=2, default=json_default) + "\n")
arith_cfg = config["arithmark3"] script = hf_hub_download(arith_cfg["repository"], arith_cfg["script"], revision=arith_cfg["revision"], repo_type="dataset") dataset = hf_hub_download(arith_cfg["repository"], arith_cfg["dataset"], revision=arith_cfg["revision"], repo_type="dataset") arith_script_sha = hashlib.sha256(Path(script).read_bytes()).hexdigest() if arith_script_sha != arith_cfg["script_sha256"]: raise RuntimeError("Pinned ArithMark script SHA-256 mismatch") arith_dir = args.output / "arithmark3" arith_dir.mkdir() old_argv = sys.argv try: sys.argv = [script, "--model", str(model_path), "--data-path", dataset, "--device", "cpu", "--dtype", "float32", "--primary-metric", "acc_norm", "--save-predictions", "--results-dir", str(arith_dir)] runpy.run_path(script, run_name="__main__") finally: sys.argv = old_argv arith_files = list(arith_dir.glob("*.json")) if len(arith_files) != 1: raise RuntimeError("Expected exactly one ArithMark output file") arith = json.loads(arith_files[0].read_text()) expected_sha = hashlib.sha256(Path(dataset).read_bytes()).hexdigest() if arith["dataset"]["sha256"] != expected_sha or len(arith["results"]["arithmark-3"]["predictions"]) != arith_cfg["examples"]: raise RuntimeError("ArithMark dataset provenance or prediction count mismatch")
aggregate = reaggregate(result, arith, config) report = {"passed": True, "protocol": config["protocol"], "model": model_source, "model_weights_sha256": weights_sha, "model_files_sha256": model_files, "runner_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "config_sha256": config_sha, "harness": harness, "evaluation_config_sha256": config_sha, "arithmark3": {"repository": arith_cfg["repository"], "revision": arith_cfg["revision"], "dataset_sha256": expected_sha, "official_script": arith_cfg["script"], "official_script_sha256": arith_script_sha}, "settings": {"device": "cpu", "dtype": "float32", "zero_shot": True, "chat_template": False, "trust_remote_code": True, "tf32": False}, **aggregate, "elapsed_seconds": time.monotonic() - started, "python": platform.python_version(), "torch": torch.__version__} (args.output / "reaggregation.json").write_text(json.dumps(report, indent=2) + "\n") print(json.dumps(report, indent=2))
if __name__ == "__main__": main()123456789# Run from the model directory so requirements.txt resolves beside this file.-r requirements.txtlm_eval @ git+https://github.com/EleutherAI/lm-evaluation-harness.git@d6de81643928d653435c431bae19945d41d32520datasets==3.1.0numpy==1.26.4pyarrow==17.0.0accelerate==0.34.2huggingface_hub>=0.26,<1.0tqdm>=4.661234torch==2.10.0tokenizers==0.20.3safetensors==0.8.0transformers==4.46.3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Transformers adapter preserving literal text and the original byte BPE."""from pathlib import Pathfrom transformers import PreTrainedTokenizerfrom .purrence_core import Sub3MTokenizer
class PurrenceTokenizer(PreTrainedTokenizer): vocab_files_names = {"vocab_file": "tokenizer/ordinary-tokenizer.json", "artifact_file": "tokenizer/artifact.json"} model_input_names = ["input_ids", "attention_mask"]
def __init__(self, vocab_file, artifact_file, **kwargs): self.native = Sub3MTokenizer(Path(artifact_file).parent) self.vocab_file = vocab_file self.artifact_file = artifact_file self.vocab = self.native.backend.get_vocab() self.vocab["<|endoftext|>"] = 2047 self.reverse_vocab = {v: k for k, v in self.vocab.items()} kwargs.setdefault("bos_token", "<|endoftext|>") kwargs.setdefault("eos_token", "<|endoftext|>") kwargs.setdefault("pad_token", "<|endoftext|>") kwargs.setdefault("model_max_length", 8192) kwargs["split_special_tokens"] = True kwargs["clean_up_tokenization_spaces"] = False super().__init__(**kwargs)
@property def vocab_size(self): return 2048
def get_vocab(self): return dict(self.vocab)
def _tokenize(self, text, **kwargs): return [self.reverse_vocab[i] for i in self.native.encode(text)]
def _convert_token_to_id(self, token): return self.vocab[token]
def _convert_id_to_token(self, index): return self.reverse_vocab[index]
def convert_tokens_to_string(self, tokens): return self.native.decode([self.vocab[t] for t in tokens])
def _decode(self, token_ids, skip_special_tokens=False, **kwargs): if isinstance(token_ids, int): token_ids = [token_ids] return self.native.decode([int(i) for i in token_ids], skip_boundaries=skip_special_tokens)
def save_vocabulary(self, save_directory, filename_prefix=None): import shutil if filename_prefix: raise ValueError("This fixed tokenizer uses canonical filenames") target = Path(save_directory) / "tokenizer" target.mkdir(parents=True, exist_ok=True) paths = [] for source in [self.vocab_file, self.artifact_file]: dest = target / Path(source).name if Path(source).resolve() != dest.resolve(): shutil.copyfile(source, dest) paths.append(str(dest)) return tuple(paths)12345678910{ "tokenizer_sha256": "fc240b741112488b639a711f502305601e3b8a1b01c5ae93a48b9ae55692dd33", "tokenizers_version": "0.20.3", "vocab_size": 2048, "boundary_special": { "id": 2047, "purpose": "structurally injected document boundary", "spelling": "<|endoftext|>" }}12345678910{ "tokenizer_class": "PurrenceTokenizer", "auto_map": {"AutoTokenizer": ["tokenization_purrence.PurrenceTokenizer", null]}, "model_max_length": 8192, "bos_token": "<|endoftext|>", "eos_token": "<|endoftext|>", "pad_token": "<|endoftext|>", "clean_up_tokenization_spaces": false, "split_special_tokens": true}.gitattributesAdded+1
README.mdAdded+195
config.jsonAdded+27
configuration_purrence.pyAdded+23
evaluation_config.jsonAdded+131
fast-attnres-LICENSEAdded+21
load_model.pyAdded+37
modded-nanogpt-LICENSEAdded+21
model.safetensorsAdded+3
modeling_purrence.pyAdded+68
purrence_core.pyAdded+216
purrence_runtime/__init__.pyAdded+1
purrence_runtime/config.pyAdded+1
purrence_runtime/model.pyAdded+1
purrence_runtime/scorer.pyAdded+117
purrence_runtime/tokenizer.pyAdded+1
reproduce_evaluation.pyAdded+292
requirements-eval.txtAdded+9
requirements.txtAdded+4
tokenization_purrence.pyAdded+63
tokenizer/artifact.jsonAdded+10
tokenizer/ordinary-tokenizer.jsonAdded
tokenizer_config.jsonAdded+10