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 files- .gitattributes +1 -0
- README.md +195 -0
- config.json +27 -0
- configuration_purrence.py +23 -0
- evaluation_config.json +131 -0
- fast-attnres-LICENSE +21 -0
- load_model.py +37 -0
- modded-nanogpt-LICENSE +21 -0
- model.safetensors +3 -0
- modeling_purrence.py +68 -0
- purrence_core.py +216 -0
- purrence_runtime/__init__.py +1 -0
- purrence_runtime/config.py +1 -0
- purrence_runtime/model.py +1 -0
- purrence_runtime/scorer.py +117 -0
- purrence_runtime/tokenizer.py +1 -0
- reproduce_evaluation.py +292 -0
- requirements-eval.txt +9 -0
- requirements.txt +4 -0
- tokenization_purrence.py +63 -0
- tokenizer/artifact.json +10 -0
- tokenizer/ordinary-tokenizer.json +0 -0
- tokenizer_config.json +10 -0
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- purrence
|
| 4 |
+
- text-generation
|
| 5 |
+
- pytorch
|
| 6 |
+
- safetensors
|
| 7 |
+
library_name: transformers
|
| 8 |
+
pipeline_tag: text-generation
|
| 9 |
+
---
|
| 10 |
+
# Purrence-3M
|
| 11 |
+
|
| 12 |
+
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.
|
| 13 |
+
|
| 14 |
+
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.
|
| 15 |
+
|
| 16 |
+
## My training blog
|
| 17 |
+
|
| 18 |
+
I share some of my training thoughts and other considerations in my blog, if you are interested in reading!
|
| 19 |
+
|
| 20 |
+
[Read my Purrence blog](https://jonathansu.me/#blogs/purrence)
|
| 21 |
+
|
| 22 |
+
## Model architecture
|
| 23 |
+
|
| 24 |
+
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.
|
| 25 |
+
|
| 26 |
+
| Field | Value |
|
| 27 |
+
|---|---|
|
| 28 |
+
| Inference parameters | 2,987,712 |
|
| 29 |
+
| Hidden size | 384 |
|
| 30 |
+
| Blocks | One shared block applied six times |
|
| 31 |
+
| Blocks stored / applied | 1 / 6 |
|
| 32 |
+
| Sequential passes | 1 |
|
| 33 |
+
| Intermediate size | 2,096 |
|
| 34 |
+
| Attention heads | 6 |
|
| 35 |
+
| Key and value heads | 6 |
|
| 36 |
+
| Head dimension | 64 |
|
| 37 |
+
| Attention | Causal multihead attention with QK normalization, per head XSA and sigmoid gates |
|
| 38 |
+
| Residual routing | LR AttnRes with rank 128 |
|
| 39 |
+
| Depth query bank | 12 learned queries of width 128, totaling 1,536 parameters |
|
| 40 |
+
| Activation | Squared ReLU in the backbone |
|
| 41 |
+
| Normalization | RMS normalization with epsilon `1e-6`. QK and routing normalization use `2^-23` |
|
| 42 |
+
| Positional encoding | Half RoPE on 32 of each head's 64 dimensions, with frequencies from 1 to 1/1,024 |
|
| 43 |
+
| Key offset | The unrotated key channels use the previous position within each document |
|
| 44 |
+
| Context length | 8,192 tokens |
|
| 45 |
+
| Vocabulary | 2,048 IDs, comprising 2,047 byte level BPE tokens and one structural boundary |
|
| 46 |
+
| Embeddings | Tied input and output, with 786,432 parameters |
|
| 47 |
+
| Logit cap | None |
|
| 48 |
+
| Released weights | FP32 Safetensors |
|
| 49 |
+
|
| 50 |
+
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.
|
| 51 |
+
|
| 52 |
+
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.
|
| 53 |
+
|
| 54 |
+
## How I trained it
|
| 55 |
+
|
| 56 |
+
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.
|
| 57 |
+
|
| 58 |
+
## What I tested
|
| 59 |
+
|
| 60 |
+
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.
|
| 61 |
+
|
| 62 |
+
### Residual routing
|
| 63 |
+
|
| 64 |
+
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.
|
| 65 |
+
|
| 66 |
+
### Loop count and training length
|
| 67 |
+
|
| 68 |
+
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.
|
| 69 |
+
|
| 70 |
+
### The NITP projector
|
| 71 |
+
|
| 72 |
+
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.
|
| 73 |
+
|
| 74 |
+
### NITP during cooldown
|
| 75 |
+
|
| 76 |
+
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.
|
| 77 |
+
|
| 78 |
+
### DeepCrossAttention
|
| 79 |
+
|
| 80 |
+
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.
|
| 81 |
+
|
| 82 |
+
### One wide block or two narrower blocks
|
| 83 |
+
|
| 84 |
+
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.
|
| 85 |
+
|
| 86 |
+
### Precision and feedforward choices
|
| 87 |
+
|
| 88 |
+
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.
|
| 89 |
+
|
| 90 |
+
### The Pulvis v2 architecture comparison
|
| 91 |
+
|
| 92 |
+
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.
|
| 93 |
+
|
| 94 |
+
### Why I abandoned two pass training
|
| 95 |
+
|
| 96 |
+
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.
|
| 97 |
+
|
| 98 |
+
## My CPU benchmark results
|
| 99 |
+
|
| 100 |
+
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.
|
| 101 |
+
|
| 102 |
+
I obtained a **normalized Intelligence Index of 8.4873**. My unrounded result was `8.487306383044526`, and my raw-accuracy index was `6.997659441758839`.
|
| 103 |
+
|
| 104 |
+
| Benchmark | Examples I evaluated | My accuracy | My normalized accuracy |
|
| 105 |
+
|---|---:|---:|---:|
|
| 106 |
+
| ARC Easy | 2,376 | 34.18% | 34.55% |
|
| 107 |
+
| ARC Challenge | 1,172 | 20.39% | 23.63% |
|
| 108 |
+
| HellaSwag | 10,042 | 27.50% | 27.81% |
|
| 109 |
+
| PIQA | 1,838 | 55.33% | 56.64% |
|
| 110 |
+
| ArithMark 3 | 1,000 | 34.80% | 34.80% |
|
| 111 |
+
| ArithMark 2 | 2,500 | 26.44% | 25.92% |
|
| 112 |
+
|
| 113 |
+
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.
|
| 114 |
+
|
| 115 |
+
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.
|
| 116 |
+
|
| 117 |
+
## Reproducing the evaluation
|
| 118 |
+
|
| 119 |
+
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.
|
| 120 |
+
|
| 121 |
+
I use Python 3.11. From the downloaded model directory, I install the evaluation dependencies and run:
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
python -m pip install -r requirements-eval.txt
|
| 125 |
+
python reproduce_evaluation.py --model . --output results
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
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:
|
| 129 |
+
|
| 130 |
+
```bash
|
| 131 |
+
python reproduce_evaluation.py --model Jonnester/Purrence-3M --output results
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
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.
|
| 135 |
+
|
| 136 |
+
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.
|
| 137 |
+
|
| 138 |
+
## How I run it
|
| 139 |
+
|
| 140 |
+
I use Python 3.11 and install the pinned dependencies from the repository directory:
|
| 141 |
+
|
| 142 |
+
```bash
|
| 143 |
+
python -m pip install -r requirements.txt
|
| 144 |
+
python load_model.py --prompt "Once upon a time" --max-new-tokens 32
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
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.
|
| 148 |
+
|
| 149 |
+
I can generate text or score continuations through the Python API:
|
| 150 |
+
|
| 151 |
+
```python
|
| 152 |
+
from load_model import load_model
|
| 153 |
+
from purrence_runtime.scorer import Scorer
|
| 154 |
+
|
| 155 |
+
model, tokenizer = load_model()
|
| 156 |
+
scorer = Scorer(model, tokenizer)
|
| 157 |
+
print(scorer.generate("Once upon a time", max_new_tokens=32))
|
| 158 |
+
print(scorer.score([(tokenizer.encode("The sky is"), tokenizer.encode(" blue."))]))
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
## How I use Transformers
|
| 162 |
+
|
| 163 |
+
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.
|
| 164 |
+
|
| 165 |
+
```python
|
| 166 |
+
import torch
|
| 167 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 168 |
+
|
| 169 |
+
repo = "Jonnester/Purrence-3M"
|
| 170 |
+
# I can set revision to a commit hash to pin this snapshot.
|
| 171 |
+
tokenizer = AutoTokenizer.from_pretrained(repo, trust_remote_code=True)
|
| 172 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 173 |
+
repo, trust_remote_code=True, torch_dtype=torch.float32
|
| 174 |
+
).eval()
|
| 175 |
+
inputs = tokenizer("Once upon a time", return_tensors="pt")
|
| 176 |
+
with torch.no_grad():
|
| 177 |
+
output = model.generate(**inputs, max_new_tokens=32, do_sample=False, use_cache=False)
|
| 178 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
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.
|
| 182 |
+
|
| 183 |
+
## My generation example
|
| 184 |
+
|
| 185 |
+
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:
|
| 186 |
+
|
| 187 |
+
```text
|
| 188 |
+
, had a far apartment border. The border was 100 million years older than the next
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
I show only the generated continuation because that is what the command prints. I reached the token limit before completing the sentence.
|
| 192 |
+
|
| 193 |
+
## My license
|
| 194 |
+
|
| 195 |
+
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.
|
config.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"vocab_size": 2048,
|
| 3 |
+
"width": 384,
|
| 4 |
+
"heads": 6,
|
| 5 |
+
"mlp_width": 2096,
|
| 6 |
+
"loops": 6,
|
| 7 |
+
"rank": 128,
|
| 8 |
+
"controller_width": 16,
|
| 9 |
+
"max_seq_len": 8192,
|
| 10 |
+
"norm_eps": 1e-06,
|
| 11 |
+
"routing_eps": 1.1920928955078125e-07,
|
| 12 |
+
"model_type": "purrence",
|
| 13 |
+
"architectures": [
|
| 14 |
+
"PurrenceForCausalLM"
|
| 15 |
+
],
|
| 16 |
+
"torch_dtype": "float32",
|
| 17 |
+
"bos_token_id": 2047,
|
| 18 |
+
"eos_token_id": 2047,
|
| 19 |
+
"pad_token_id": 2047,
|
| 20 |
+
"tie_word_embeddings": true,
|
| 21 |
+
"use_cache": false,
|
| 22 |
+
"max_position_embeddings": 8192,
|
| 23 |
+
"auto_map": {
|
| 24 |
+
"AutoConfig": "configuration_purrence.PurrenceConfig",
|
| 25 |
+
"AutoModelForCausalLM": "modeling_purrence.PurrenceForCausalLM"
|
| 26 |
+
}
|
| 27 |
+
}
|
configuration_purrence.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configuration for the fixed Purrence-3M inference architecture."""
|
| 2 |
+
from dataclasses import asdict
|
| 3 |
+
from transformers import PretrainedConfig
|
| 4 |
+
from .purrence_core import ModelConfig
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class PurrenceConfig(PretrainedConfig):
|
| 8 |
+
model_type = "purrence"
|
| 9 |
+
|
| 10 |
+
def __init__(self, **kwargs):
|
| 11 |
+
dimensions = asdict(ModelConfig())
|
| 12 |
+
for name, default in dimensions.items():
|
| 13 |
+
dimensions[name] = kwargs.pop(name, default)
|
| 14 |
+
ModelConfig(**dimensions).validate()
|
| 15 |
+
kwargs.setdefault("bos_token_id", 2047)
|
| 16 |
+
kwargs.setdefault("eos_token_id", 2047)
|
| 17 |
+
kwargs.setdefault("pad_token_id", 2047)
|
| 18 |
+
kwargs.setdefault("tie_word_embeddings", True)
|
| 19 |
+
super().__init__(**kwargs)
|
| 20 |
+
for name, value in dimensions.items():
|
| 21 |
+
setattr(self, name, value)
|
| 22 |
+
self.max_position_embeddings = self.max_seq_len
|
| 23 |
+
self.use_cache = False
|
evaluation_config.json
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": 1,
|
| 3 |
+
"protocol": "local-pinned-open-slm-zero-shot-v2",
|
| 4 |
+
"harness": {
|
| 5 |
+
"distribution": "lm_eval",
|
| 6 |
+
"repository": "https://github.com/EleutherAI/lm-evaluation-harness",
|
| 7 |
+
"revision": "d6de81643928d653435c431bae19945d41d32520",
|
| 8 |
+
"python_requires": ">=3.10",
|
| 9 |
+
"task_configs": {
|
| 10 |
+
"arc_easy": "lm_eval/tasks/arc/arc_easy.yaml",
|
| 11 |
+
"arc_challenge": "lm_eval/tasks/arc/arc_challenge.yaml",
|
| 12 |
+
"hellaswag": "lm_eval/tasks/hellaswag/hellaswag.yaml",
|
| 13 |
+
"piqa": "lm_eval/tasks/piqa/piqa.yaml"
|
| 14 |
+
}
|
| 15 |
+
},
|
| 16 |
+
"arithmark3": {
|
| 17 |
+
"repository": "AxiomicLabs/Arithmark-3.0",
|
| 18 |
+
"revision": "6f6e59dd9b7e2c63455f7af7f838f9ecc3d0a746",
|
| 19 |
+
"script": "bencharithmark-3.py",
|
| 20 |
+
"dataset": "arithmark-3.jsonl",
|
| 21 |
+
"examples": 1000,
|
| 22 |
+
"script_sha256": "09667e1ea05ecd8b91dbfea14a47365b555c72622afed9fc284c127ecd5e1bcd"
|
| 23 |
+
},
|
| 24 |
+
"model": {
|
| 25 |
+
"default_repo": "Jonnester/Purrence-3M",
|
| 26 |
+
"device": "cpu",
|
| 27 |
+
"dtype": "float32",
|
| 28 |
+
"trust_remote_code": true,
|
| 29 |
+
"batch_size": 16,
|
| 30 |
+
"max_length": 8192,
|
| 31 |
+
"add_bos_token": false,
|
| 32 |
+
"default_local_path": ".",
|
| 33 |
+
"expected_weights_sha256": "9c9f8d29004ce3563090de3c9be42059c5e2f928e053d4b17637f2215d7972ec",
|
| 34 |
+
"expected_file_sha256": {
|
| 35 |
+
"config.json": "a82f737624152185ff9afd9573a2d82e3592fcd3f61df9dbdac25188e25c659e",
|
| 36 |
+
"modeling_purrence.py": "6467854a7a53185b2ed2693cf0f9d0150898a13efb35cf0c12cd3b53691ca817",
|
| 37 |
+
"configuration_purrence.py": "a33340909d58f0505262f5111ed41da0faa4222ee99a439cd93c700c3c9c30ee",
|
| 38 |
+
"tokenization_purrence.py": "c25e6e0e712e754e2f6d09a45899f84a90a611a7b32ac43515b9cd09c075dfec",
|
| 39 |
+
"purrence_core.py": "0141fff6cc77cc590145873fa754a6fec1aeec67cc19be4d8a9dce769728c02b",
|
| 40 |
+
"tokenizer_config.json": "69bfe2ccb62a039a97e6df0ca4a670440170eae950aa735760cbf0e95db962e5",
|
| 41 |
+
"tokenizer/ordinary-tokenizer.json": "fc240b741112488b639a711f502305601e3b8a1b01c5ae93a48b9ae55692dd33",
|
| 42 |
+
"tokenizer/artifact.json": "4c2241f6f7deffc43043ae1e91eea87434de6725bf0c4e5d2dfe5a45588733bd"
|
| 43 |
+
}
|
| 44 |
+
},
|
| 45 |
+
"evaluation": {
|
| 46 |
+
"precision": "fp32",
|
| 47 |
+
"num_fewshot": 0,
|
| 48 |
+
"limit": null,
|
| 49 |
+
"apply_chat_template": false,
|
| 50 |
+
"system_instruction": null,
|
| 51 |
+
"log_samples": true,
|
| 52 |
+
"seeds": {
|
| 53 |
+
"random": 17,
|
| 54 |
+
"numpy": 17,
|
| 55 |
+
"torch": 17,
|
| 56 |
+
"fewshot": 17
|
| 57 |
+
},
|
| 58 |
+
"bootstrap_iters": 1000,
|
| 59 |
+
"metrics": [
|
| 60 |
+
"acc",
|
| 61 |
+
"acc_norm"
|
| 62 |
+
]
|
| 63 |
+
},
|
| 64 |
+
"tasks": {
|
| 65 |
+
"arc_easy": {
|
| 66 |
+
"task_version": 1.0,
|
| 67 |
+
"dataset_path": "allenai/ai2_arc",
|
| 68 |
+
"dataset_name": "ARC-Easy",
|
| 69 |
+
"storage_adapter": {
|
| 70 |
+
"dataset_name": null,
|
| 71 |
+
"data_dir": "ARC-Easy"
|
| 72 |
+
},
|
| 73 |
+
"dataset_revision": "54cd56ea77687f84868e2cb8d58e3f462bdd0d45",
|
| 74 |
+
"evaluation_split": "test",
|
| 75 |
+
"examples": 2376,
|
| 76 |
+
"chance": 0.25,
|
| 77 |
+
"metrics": [
|
| 78 |
+
"acc",
|
| 79 |
+
"acc_norm"
|
| 80 |
+
]
|
| 81 |
+
},
|
| 82 |
+
"arc_challenge": {
|
| 83 |
+
"task_version": 1.0,
|
| 84 |
+
"dataset_path": "allenai/ai2_arc",
|
| 85 |
+
"dataset_name": "ARC-Challenge",
|
| 86 |
+
"storage_adapter": {
|
| 87 |
+
"dataset_name": null,
|
| 88 |
+
"data_dir": "ARC-Challenge"
|
| 89 |
+
},
|
| 90 |
+
"dataset_revision": "54cd56ea77687f84868e2cb8d58e3f462bdd0d45",
|
| 91 |
+
"evaluation_split": "test",
|
| 92 |
+
"examples": 1172,
|
| 93 |
+
"chance": 0.25,
|
| 94 |
+
"metrics": [
|
| 95 |
+
"acc",
|
| 96 |
+
"acc_norm"
|
| 97 |
+
]
|
| 98 |
+
},
|
| 99 |
+
"hellaswag": {
|
| 100 |
+
"task_version": 1.0,
|
| 101 |
+
"dataset_path": "Rowan/hellaswag",
|
| 102 |
+
"dataset_name": null,
|
| 103 |
+
"dataset_revision": "218ec52e09a7e7462a5400043bb9a69a41d06b76",
|
| 104 |
+
"evaluation_split": "validation",
|
| 105 |
+
"examples": 10042,
|
| 106 |
+
"chance": 0.25,
|
| 107 |
+
"metrics": [
|
| 108 |
+
"acc",
|
| 109 |
+
"acc_norm"
|
| 110 |
+
]
|
| 111 |
+
},
|
| 112 |
+
"piqa": {
|
| 113 |
+
"task_version": 1.0,
|
| 114 |
+
"dataset_path": "baber/piqa",
|
| 115 |
+
"dataset_name": null,
|
| 116 |
+
"dataset_revision": "142f6d7367fd9877f0fb3b5734ea6a545f54cdd1",
|
| 117 |
+
"evaluation_split": "validation",
|
| 118 |
+
"examples": 1838,
|
| 119 |
+
"chance": 0.5,
|
| 120 |
+
"metrics": [
|
| 121 |
+
"acc",
|
| 122 |
+
"acc_norm"
|
| 123 |
+
]
|
| 124 |
+
}
|
| 125 |
+
},
|
| 126 |
+
"index": {
|
| 127 |
+
"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",
|
| 128 |
+
"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",
|
| 129 |
+
"note": "Leaderboard formula applied to these local measurements; independent leaderboard verification is not implied."
|
| 130 |
+
}
|
| 131 |
+
}
|
fast-attnres-LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Jonnester
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
load_model.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load the inference-only FP32 Purrence package without training state."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from dataclasses import fields
|
| 6 |
+
import torch
|
| 7 |
+
from safetensors.torch import load_file
|
| 8 |
+
from purrence_runtime.config import ModelConfig
|
| 9 |
+
from purrence_runtime.model import RecurrentLM
|
| 10 |
+
from purrence_runtime.tokenizer import Sub3MTokenizer
|
| 11 |
+
from purrence_runtime.scorer import Scorer
|
| 12 |
+
|
| 13 |
+
def load_model(directory=None, device="cpu"):
|
| 14 |
+
root = Path(directory) if directory else Path(__file__).resolve().parent
|
| 15 |
+
values = json.loads((root / "config.json").read_text())
|
| 16 |
+
config = ModelConfig(**{f.name: values[f.name] for f in fields(ModelConfig)})
|
| 17 |
+
model = RecurrentLM(config)
|
| 18 |
+
state = load_file(str(root / "model.safetensors"), device="cpu")
|
| 19 |
+
model.load_state_dict(state, strict=True)
|
| 20 |
+
if any(not torch.isfinite(p).all() for p in model.parameters()):
|
| 21 |
+
raise ValueError("Nonfinite model weights")
|
| 22 |
+
if model.parameter_count() != 2987712:
|
| 23 |
+
raise ValueError("Inference parameter count differs from the qualified model")
|
| 24 |
+
model = model.to(device).float().eval()
|
| 25 |
+
tokenizer = Sub3MTokenizer(root / "tokenizer")
|
| 26 |
+
return model, tokenizer
|
| 27 |
+
|
| 28 |
+
if __name__ == "__main__":
|
| 29 |
+
p = argparse.ArgumentParser()
|
| 30 |
+
p.add_argument("--directory", type=Path)
|
| 31 |
+
p.add_argument("--device", default="cpu")
|
| 32 |
+
p.add_argument("--prompt", default="Once upon a time")
|
| 33 |
+
p.add_argument("--max-new-tokens", type=int, default=32)
|
| 34 |
+
args = p.parse_args()
|
| 35 |
+
torch.set_num_threads(2)
|
| 36 |
+
model, tokenizer = load_model(args.directory, args.device)
|
| 37 |
+
print(Scorer(model, tokenizer).generate(args.prompt, max_new_tokens=args.max_new_tokens))
|
modded-nanogpt-LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2024 Keller Jordan
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c9f8d29004ce3563090de3c9be42059c5e2f928e053d4b17637f2215d7972ec
|
| 3 |
+
size 11951728
|
modeling_purrence.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transformers inference adapter using the unchanged native model equations."""
|
| 2 |
+
from dataclasses import fields
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import PreTrainedModel, GenerationMixin
|
| 5 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 6 |
+
from .configuration_purrence import PurrenceConfig
|
| 7 |
+
from .purrence_core import ModelConfig, RecurrentLM
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class PurrenceForCausalLM(PreTrainedModel, GenerationMixin):
|
| 11 |
+
config_class = PurrenceConfig
|
| 12 |
+
base_model_prefix = ""
|
| 13 |
+
main_input_name = "input_ids"
|
| 14 |
+
_supports_cache_class = False
|
| 15 |
+
|
| 16 |
+
def __init__(self, config, dtype=None):
|
| 17 |
+
super().__init__(config)
|
| 18 |
+
native = RecurrentLM(ModelConfig(**{
|
| 19 |
+
f.name: getattr(config, f.name) for f in fields(ModelConfig)
|
| 20 |
+
}))
|
| 21 |
+
self.embedding = native.embedding
|
| 22 |
+
self.block = native.block
|
| 23 |
+
self.queries = native.queries
|
| 24 |
+
|
| 25 |
+
def get_input_embeddings(self):
|
| 26 |
+
return self.embedding
|
| 27 |
+
|
| 28 |
+
def set_input_embeddings(self, value):
|
| 29 |
+
self.embedding = value
|
| 30 |
+
|
| 31 |
+
def get_output_embeddings(self):
|
| 32 |
+
return None # The native forward uses the embedding weight directly.
|
| 33 |
+
|
| 34 |
+
def read(self, sources, query):
|
| 35 |
+
return RecurrentLM.read(self, sources, query)
|
| 36 |
+
|
| 37 |
+
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
|
| 38 |
+
return dict(input_ids=input_ids, attention_mask=attention_mask, use_cache=False)
|
| 39 |
+
|
| 40 |
+
def forward(self, input_ids=None, attention_mask=None, return_dict=None,
|
| 41 |
+
use_cache=False, past_key_values=None, labels=None, **kwargs):
|
| 42 |
+
if labels is not None or past_key_values is not None:
|
| 43 |
+
raise ValueError("This inference adapter does not implement training or a KV cache")
|
| 44 |
+
if input_ids is None or input_ids.ndim != 2 or input_ids.numel() == 0:
|
| 45 |
+
raise ValueError("Expected a nonempty batch of token IDs")
|
| 46 |
+
if attention_mask is None:
|
| 47 |
+
mask = torch.ones_like(input_ids, dtype=torch.bool)
|
| 48 |
+
else:
|
| 49 |
+
if attention_mask.shape != input_ids.shape:
|
| 50 |
+
raise ValueError("Attention mask shape differs from input IDs")
|
| 51 |
+
mask = attention_mask.bool()
|
| 52 |
+
lengths = mask.sum(-1)
|
| 53 |
+
if (lengths == 0).any() or (lengths > self.config.max_seq_len).any():
|
| 54 |
+
raise ValueError("Each sequence must contain 1 to 8192 unmasked tokens")
|
| 55 |
+
packed = input_ids[mask]
|
| 56 |
+
starts = torch.cat((lengths.new_zeros(1), lengths.cumsum(0)[:-1]))
|
| 57 |
+
document_starts = packed.eq(self.config.eos_token_id)
|
| 58 |
+
document_starts[starts] = True
|
| 59 |
+
offsets = document_starts.nonzero().flatten()
|
| 60 |
+
cu = torch.cat((offsets, offsets.new_tensor([packed.numel()]))).to(torch.int32)
|
| 61 |
+
positions = torch.arange(packed.numel(), device=packed.device) - torch.repeat_interleave(offsets, cu.diff().long())
|
| 62 |
+
with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.MATH):
|
| 63 |
+
values = RecurrentLM.forward(self, packed, cu, positions)
|
| 64 |
+
logits = values.new_zeros((*input_ids.shape, self.config.vocab_size))
|
| 65 |
+
logits[mask] = values
|
| 66 |
+
if return_dict is False or (return_dict is None and not self.config.use_return_dict):
|
| 67 |
+
return (logits,)
|
| 68 |
+
return CausalLMOutput(logits=logits)
|
purrence_core.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Architecture dimensions of the fixed inference export."""
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@dataclass(frozen=True)
|
| 6 |
+
class ModelConfig:
|
| 7 |
+
vocab_size: int = 2048
|
| 8 |
+
width: int = 384
|
| 9 |
+
heads: int = 6
|
| 10 |
+
mlp_width: int = 2096
|
| 11 |
+
loops: int = 6
|
| 12 |
+
rank: int = 128
|
| 13 |
+
controller_width: int = 16
|
| 14 |
+
max_seq_len: int = 8192
|
| 15 |
+
norm_eps: float = 1e-06
|
| 16 |
+
routing_eps: float = 1.1920928955078125e-07
|
| 17 |
+
|
| 18 |
+
def validate(self):
|
| 19 |
+
if self != ModelConfig():
|
| 20 |
+
raise ValueError("This runtime supports the released Purrence architecture only")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
"""Six-loop Attention Residuals inference with per-head XSA and gates."""
|
| 24 |
+
import torch
|
| 25 |
+
from torch import nn
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def rms(x, eps):
|
| 30 |
+
work = x if x.dtype == torch.float64 else x.float()
|
| 31 |
+
return (work * torch.rsqrt(work.square().mean(-1, keepdim=True) + eps)).to(x.dtype)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def depth_read(sources, query, eps=2 ** -23):
|
| 35 |
+
values = torch.stack(sources)
|
| 36 |
+
work = values if values.dtype == torch.float64 else values.float()
|
| 37 |
+
inverse_rms = torch.rsqrt(work.square().mean(-1) + eps)
|
| 38 |
+
scores = (work[..., -query.numel():] * query.to(work.dtype)).sum(-1) * inverse_rms
|
| 39 |
+
weights = scores.softmax(dim=0)
|
| 40 |
+
return (weights[..., None] * work).sum(0).to(values.dtype)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def document_layout(ids, boundary_id):
|
| 44 |
+
flat = ids.reshape(-1)
|
| 45 |
+
starts = flat.eq(boundary_id)
|
| 46 |
+
starts[0] = True
|
| 47 |
+
if ids.ndim == 2:
|
| 48 |
+
starts[::ids.shape[1]] = True
|
| 49 |
+
offsets = starts.nonzero().flatten()
|
| 50 |
+
cu = torch.cat((offsets, offsets.new_tensor([flat.numel()]))).to(torch.int32)
|
| 51 |
+
positions = torch.arange(flat.numel(), device=ids.device) - torch.repeat_interleave(offsets, cu.diff().long())
|
| 52 |
+
return cu, positions
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def half_rope(x, positions, frequencies, factors=None):
|
| 56 |
+
rotary_dim = x.shape[-1] // 2
|
| 57 |
+
if factors is None:
|
| 58 |
+
angle = positions.float()[:, None] * frequencies[None]
|
| 59 |
+
cosine, sine = angle.cos().to(x.dtype)[:, None], angle.sin().to(x.dtype)[:, None]
|
| 60 |
+
else:
|
| 61 |
+
cosine, sine = (factor.to(x.dtype) for factor in factors)
|
| 62 |
+
even, odd = x[..., :rotary_dim:2], x[..., 1:rotary_dim:2]
|
| 63 |
+
rotated = torch.stack((even * cosine + odd * sine, odd * cosine - even * sine), dim=-1)
|
| 64 |
+
return torch.cat((rotated.flatten(-2), x[..., rotary_dim:]), dim=-1)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def offset_keys(keys, positions):
|
| 68 |
+
rotary_dim = keys.shape[-1] // 2
|
| 69 |
+
previous = torch.cat((keys[:1, :, rotary_dim:], keys[:-1, :, rotary_dim:]))
|
| 70 |
+
stationary = torch.where(positions[:, None, None] > 0, previous, keys[..., rotary_dim:])
|
| 71 |
+
return torch.cat((keys[..., :rotary_dim], stationary), dim=-1)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def attention(q, k, v, cu):
|
| 75 |
+
result = []
|
| 76 |
+
boundaries = cu.tolist()
|
| 77 |
+
for start, end in zip(boundaries, boundaries[1:]):
|
| 78 |
+
query, key, value = (item[start:end].transpose(0, 1)[None] for item in (q, k, v))
|
| 79 |
+
out = F.scaled_dot_product_attention(query, key, value, is_causal=True)
|
| 80 |
+
result.append(out[0].transpose(0, 1))
|
| 81 |
+
return torch.cat(result)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class SharedBlock(nn.Module):
|
| 85 |
+
def __init__(self, config):
|
| 86 |
+
super().__init__()
|
| 87 |
+
self.config = config
|
| 88 |
+
self.q = nn.Linear(config.width, config.width, bias=False)
|
| 89 |
+
self.k = nn.Linear(config.width, config.width, bias=False)
|
| 90 |
+
self.v = nn.Linear(config.width, config.width, bias=False)
|
| 91 |
+
self.o = nn.Linear(config.width, config.width, bias=False)
|
| 92 |
+
self.up = nn.Linear(config.width, config.mlp_width, bias=False)
|
| 93 |
+
self.down = nn.Linear(config.mlp_width, config.width, bias=False)
|
| 94 |
+
self.xsa = nn.Linear(config.controller_width, config.heads, bias=False)
|
| 95 |
+
self.gate = nn.Linear(config.controller_width, config.heads, bias=False)
|
| 96 |
+
head_dim = config.width // config.heads
|
| 97 |
+
self.register_buffer("frequencies", (1 / 1024) ** torch.linspace(0, 1, head_dim // 4), persistent=False)
|
| 98 |
+
|
| 99 |
+
def rotary_factors(self, positions, dtype):
|
| 100 |
+
angle = positions.float()[:, None] * self.frequencies[None]
|
| 101 |
+
return angle.cos().to(dtype)[:, None], angle.sin().to(dtype)[:, None]
|
| 102 |
+
|
| 103 |
+
def attend(self, x, cu, positions, rope_factors):
|
| 104 |
+
config = self.config
|
| 105 |
+
q, k, v = [F.linear(x, getattr(self, name).weight.to(x.dtype)).view(
|
| 106 |
+
-1, config.heads, config.width // config.heads) for name in ('q', 'k', 'v')]
|
| 107 |
+
q = half_rope(rms(q, config.routing_eps), positions, self.frequencies, rope_factors)
|
| 108 |
+
k = half_rope(rms(k, config.routing_eps), positions, self.frequencies, rope_factors)
|
| 109 |
+
k = offset_keys(k, positions)
|
| 110 |
+
y = attention(q, k, v, cu)
|
| 111 |
+
local = x[..., :config.controller_width]
|
| 112 |
+
alpha, gate = self.xsa(local), self.gate(local)
|
| 113 |
+
dot = (y * v).sum(-1, keepdim=True)
|
| 114 |
+
denominator = v.square().sum(-1, keepdim=True).clamp_min(1e-8)
|
| 115 |
+
y = y - alpha.tanh().to(y.dtype)[..., None] * (dot / denominator) * v
|
| 116 |
+
y = y * gate.sigmoid().to(y.dtype)[..., None]
|
| 117 |
+
return F.linear(y.contiguous().flatten(-2), self.o.weight.to(y.dtype))
|
| 118 |
+
|
| 119 |
+
def mlp(self, x):
|
| 120 |
+
return self.down(self.up(x).relu().square())
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class RecurrentLM(nn.Module):
|
| 124 |
+
def __init__(self, config=None):
|
| 125 |
+
super().__init__()
|
| 126 |
+
self.config = config or ModelConfig()
|
| 127 |
+
self.config.validate()
|
| 128 |
+
self.embedding = nn.Embedding(self.config.vocab_size, self.config.width)
|
| 129 |
+
self.block = SharedBlock(self.config)
|
| 130 |
+
self.queries = nn.Parameter(torch.zeros(2 * self.config.loops, self.config.rank))
|
| 131 |
+
|
| 132 |
+
def read(self, sources, query):
|
| 133 |
+
x = sources[0] if query is None else depth_read(sources, query, self.config.routing_eps)
|
| 134 |
+
return rms(x, self.config.norm_eps)
|
| 135 |
+
|
| 136 |
+
def forward(self, ids, cu_seqlens=None, positions=None):
|
| 137 |
+
if ids.ndim not in (1, 2) or ids.numel() == 0:
|
| 138 |
+
raise ValueError("Expected nonempty one- or two-dimensional token IDs")
|
| 139 |
+
if cu_seqlens is None:
|
| 140 |
+
cu_seqlens, positions = document_layout(ids, self.config.vocab_size - 1)
|
| 141 |
+
if positions is None:
|
| 142 |
+
raise ValueError("Explicit packed boundaries require explicit document positions")
|
| 143 |
+
if int(cu_seqlens.diff().max()) > self.config.max_seq_len:
|
| 144 |
+
raise ValueError("Document segment exceeds max_seq_len")
|
| 145 |
+
embedding = self.embedding(ids.reshape(-1))
|
| 146 |
+
rope_factors = self.block.rotary_factors(positions, embedding.dtype)
|
| 147 |
+
sources = [embedding]
|
| 148 |
+
for loop in range(self.config.loops):
|
| 149 |
+
x = self.read(sources, None if loop == 0 else self.queries[2 * loop - 1])
|
| 150 |
+
a = self.block.attend(x, cu_seqlens, positions, rope_factors)
|
| 151 |
+
x = self.read(sources + [a], self.queries[2 * loop])
|
| 152 |
+
m = self.block.mlp(x)
|
| 153 |
+
sources.append(a + m)
|
| 154 |
+
x = self.read(sources, self.queries[-1])
|
| 155 |
+
return F.linear(x, self.embedding.weight).view(*ids.shape, self.config.vocab_size)
|
| 156 |
+
|
| 157 |
+
def parameter_count(self):
|
| 158 |
+
return sum(parameter.numel() for parameter in self.parameters())
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
#!/usr/bin/env python3
|
| 162 |
+
"""Small runtime for the reviewed 2048-ID tokenizer and structural boundaries."""
|
| 163 |
+
import hashlib
|
| 164 |
+
import json
|
| 165 |
+
from pathlib import Path
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class Sub3MTokenizer:
|
| 169 |
+
vocab_size = 2048
|
| 170 |
+
boundary_id = 2047
|
| 171 |
+
|
| 172 |
+
def __init__(self, artifact_dir):
|
| 173 |
+
import tokenizers
|
| 174 |
+
directory = Path(artifact_dir)
|
| 175 |
+
metadata = json.loads((directory / "artifact.json").read_text(encoding="utf-8"))
|
| 176 |
+
if tokenizers.__version__ != metadata["tokenizers_version"]:
|
| 177 |
+
raise RuntimeError("Use tokenizers==" + metadata["tokenizers_version"])
|
| 178 |
+
path = directory / "ordinary-tokenizer.json"
|
| 179 |
+
if hashlib.sha256(path.read_bytes()).hexdigest() != metadata["tokenizer_sha256"]:
|
| 180 |
+
raise ValueError("Tokenizer file does not match its artifact hash")
|
| 181 |
+
self.backend = tokenizers.Tokenizer.from_file(str(path))
|
| 182 |
+
if self.backend.get_vocab_size() != 2047 or metadata["vocab_size"] != 2048:
|
| 183 |
+
raise ValueError("Expected 2047 ordinary IDs and one structural boundary")
|
| 184 |
+
if json.loads(path.read_text(encoding="utf-8")).get("added_tokens"):
|
| 185 |
+
raise ValueError("Ordinary encoder must not recognize structural token spellings")
|
| 186 |
+
self.metadata = metadata
|
| 187 |
+
|
| 188 |
+
def encode(self, text):
|
| 189 |
+
"""Encode literal text; even '<|endoftext|>' remains ordinary content."""
|
| 190 |
+
if not isinstance(text, str):
|
| 191 |
+
raise TypeError("encode expects a Unicode string")
|
| 192 |
+
ids = self.backend.encode(text, add_special_tokens=False).ids
|
| 193 |
+
if any(token_id >= self.boundary_id for token_id in ids):
|
| 194 |
+
raise ValueError("Ordinary encoding emitted a reserved ID")
|
| 195 |
+
return ids
|
| 196 |
+
|
| 197 |
+
def decode(self, ids, skip_boundaries=False):
|
| 198 |
+
"""Decode generated IDs; optionally omit structural boundary markers.
|
| 199 |
+
|
| 200 |
+
Arbitrary generated byte sequences can be invalid UTF-8; the ByteLevel
|
| 201 |
+
decoder replaces invalid sequences. Every encoded valid string roundtrips.
|
| 202 |
+
"""
|
| 203 |
+
chunks = []
|
| 204 |
+
ordinary = []
|
| 205 |
+
for token_id in ids:
|
| 206 |
+
if type(token_id) is not int or token_id not in range(self.vocab_size):
|
| 207 |
+
raise ValueError("Token ID must be an integer in [0, 2048)")
|
| 208 |
+
if token_id == self.boundary_id:
|
| 209 |
+
chunks.append(self.backend.decode(ordinary, skip_special_tokens=False))
|
| 210 |
+
ordinary = []
|
| 211 |
+
if not skip_boundaries:
|
| 212 |
+
chunks.append(self.metadata["boundary_special"]["spelling"])
|
| 213 |
+
else:
|
| 214 |
+
ordinary.append(token_id)
|
| 215 |
+
chunks.append(self.backend.decode(ordinary, skip_special_tokens=False))
|
| 216 |
+
return "".join(chunks)
|
purrence_runtime/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""FP32 inference for the released Purrence model."""
|
purrence_runtime/config.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from purrence_core import ModelConfig
|
purrence_runtime/model.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from purrence_core import RecurrentLM
|
purrence_runtime/scorer.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import contextmanager
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from .tokenizer import Sub3MTokenizer
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
TOKENIZER = Path(__file__).resolve().parents[1] / "tokenizer"
|
| 7 |
+
def cross_entropy_sum(logits, targets):
|
| 8 |
+
return F.cross_entropy(logits.float(), targets, reduction="sum")
|
| 9 |
+
|
| 10 |
+
@contextmanager
|
| 11 |
+
def fp32_math(device):
|
| 12 |
+
"""Full FP32 inference, including attention, without leaking backend flags."""
|
| 13 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
| 14 |
+
previous_precision = torch.get_float32_matmul_precision()
|
| 15 |
+
previous_tf32 = torch.backends.cuda.matmul.allow_tf32
|
| 16 |
+
previous_cudnn_tf32 = torch.backends.cudnn.allow_tf32
|
| 17 |
+
try:
|
| 18 |
+
torch.set_float32_matmul_precision("highest")
|
| 19 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 20 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 21 |
+
with torch.autocast(device.type, enabled=False), sdpa_kernel(SDPBackend.MATH):
|
| 22 |
+
yield
|
| 23 |
+
finally:
|
| 24 |
+
torch.set_float32_matmul_precision(previous_precision)
|
| 25 |
+
torch.backends.cuda.matmul.allow_tf32 = previous_tf32
|
| 26 |
+
torch.backends.cudnn.allow_tf32 = previous_cudnn_tf32
|
| 27 |
+
|
| 28 |
+
class Scorer:
|
| 29 |
+
def __init__(self, model, tokenizer=None, batch_size=16):
|
| 30 |
+
if batch_size < 1:
|
| 31 |
+
raise ValueError("Batch size must be positive")
|
| 32 |
+
self.model = model.eval()
|
| 33 |
+
self.tokenizer = tokenizer or Sub3MTokenizer(TOKENIZER)
|
| 34 |
+
self.batch_size = batch_size
|
| 35 |
+
self.device = next(model.parameters()).device
|
| 36 |
+
if any(p.is_floating_point() and p.dtype != torch.float32
|
| 37 |
+
for p in model.parameters()):
|
| 38 |
+
raise ValueError("This scorer requires FP32 inference weights")
|
| 39 |
+
|
| 40 |
+
def inference_context(self):
|
| 41 |
+
return fp32_math(self.device)
|
| 42 |
+
|
| 43 |
+
@torch.no_grad()
|
| 44 |
+
def score(self, requests, max_length=None):
|
| 45 |
+
limit = max_length or self.model.config.max_seq_len
|
| 46 |
+
if not 1 <= limit <= self.model.config.max_seq_len:
|
| 47 |
+
raise ValueError("Scoring context is outside the model's context limit")
|
| 48 |
+
results = []
|
| 49 |
+
for begin in range(0, len(requests), self.batch_size):
|
| 50 |
+
inputs, targets, lengths, counts = [], [], [], []
|
| 51 |
+
for context, continuation in requests[begin:begin + self.batch_size]:
|
| 52 |
+
if not continuation or len(continuation) > limit:
|
| 53 |
+
raise ValueError("Continuation must contain between one and max_length tokens")
|
| 54 |
+
context = context or [self.tokenizer.boundary_id]
|
| 55 |
+
sequence = (list(context) + list(continuation))[-(limit + 1):]
|
| 56 |
+
inputs.extend(sequence[:-1])
|
| 57 |
+
targets.append(continuation)
|
| 58 |
+
lengths.append(len(sequence) - 1)
|
| 59 |
+
counts.append(len(continuation))
|
| 60 |
+
ids = torch.tensor(inputs, dtype=torch.long, device=self.device)
|
| 61 |
+
cu = F.pad(torch.tensor(lengths, device=self.device).cumsum(0), (1, 0)).to(torch.int32)
|
| 62 |
+
positions = torch.cat([torch.arange(length, device=self.device) for length in lengths])
|
| 63 |
+
with self.inference_context():
|
| 64 |
+
logits = self.model(ids, cu, positions)
|
| 65 |
+
offset = 0
|
| 66 |
+
for length, count, target in zip(lengths, counts, targets):
|
| 67 |
+
selected = logits[offset + length - count:offset + length].float()
|
| 68 |
+
target = torch.tensor(target, device=self.device)
|
| 69 |
+
value = -cross_entropy_sum(selected, target)
|
| 70 |
+
greedy = selected.argmax(-1).eq(target).all()
|
| 71 |
+
results.append((float(value), bool(greedy)))
|
| 72 |
+
offset += length
|
| 73 |
+
return results
|
| 74 |
+
|
| 75 |
+
def rolling(self, text):
|
| 76 |
+
tokens = self.tokenizer.encode(text)
|
| 77 |
+
limit = self.model.config.max_seq_len
|
| 78 |
+
requests = []
|
| 79 |
+
for start in range(0, len(tokens), limit):
|
| 80 |
+
continuation = tokens[start:start + limit]
|
| 81 |
+
if not start:
|
| 82 |
+
context = [self.tokenizer.boundary_id]
|
| 83 |
+
elif len(continuation) < limit:
|
| 84 |
+
# LM-Eval's final partial window keeps enough preceding tokens
|
| 85 |
+
# to use the full model context; full-sized windows keep one.
|
| 86 |
+
context_size = limit - len(continuation) + 1
|
| 87 |
+
context = tokens[start - context_size:start]
|
| 88 |
+
else:
|
| 89 |
+
context = [tokens[start - 1]]
|
| 90 |
+
requests.append((context, continuation))
|
| 91 |
+
return sum(score for score, _ in self.score(requests))
|
| 92 |
+
|
| 93 |
+
@torch.no_grad()
|
| 94 |
+
def generate(self, prompt, max_new_tokens=128, temperature=0.0, until=(), seed=17):
|
| 95 |
+
if max_new_tokens < 0 or temperature < 0:
|
| 96 |
+
raise ValueError("Generation length and temperature must be nonnegative")
|
| 97 |
+
if isinstance(until, str):
|
| 98 |
+
until = [until]
|
| 99 |
+
if any(not stop for stop in until):
|
| 100 |
+
raise ValueError("Stop strings must be nonempty")
|
| 101 |
+
prefix = self.tokenizer.encode(prompt) or [self.tokenizer.boundary_id]
|
| 102 |
+
generated = []
|
| 103 |
+
rng = torch.Generator(device=self.device).manual_seed(seed)
|
| 104 |
+
for _ in range(max_new_tokens):
|
| 105 |
+
ids = torch.tensor((prefix + generated)[-self.model.config.max_seq_len:], device=self.device)
|
| 106 |
+
with self.inference_context():
|
| 107 |
+
logits = self.model(ids)[-1].float()
|
| 108 |
+
token = int(logits.argmax()) if temperature == 0 else int(torch.multinomial(
|
| 109 |
+
(logits / temperature).softmax(-1), 1, generator=rng))
|
| 110 |
+
if token == self.tokenizer.boundary_id:
|
| 111 |
+
break
|
| 112 |
+
generated.append(token)
|
| 113 |
+
text = self.tokenizer.decode(generated)
|
| 114 |
+
endings = [text.index(stop) for stop in until if stop in text]
|
| 115 |
+
if endings:
|
| 116 |
+
return text[:min(endings)]
|
| 117 |
+
return self.tokenizer.decode(generated)
|
purrence_runtime/tokenizer.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from purrence_core import Sub3MTokenizer
|
reproduce_evaluation.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Reproduce Purrence's documented five-task CPU FP32 evaluation."""
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import platform
|
| 9 |
+
import runpy
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parent
|
| 15 |
+
CONFIG_PATH = ROOT / "evaluation_config.json"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def read_config():
|
| 19 |
+
raw = CONFIG_PATH.read_bytes()
|
| 20 |
+
return json.loads(raw), hashlib.sha256(raw).hexdigest()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def verify_model_files(model_path, config):
|
| 24 |
+
actual = {}
|
| 25 |
+
for filename, expected in config["model"]["expected_file_sha256"].items():
|
| 26 |
+
path = model_path / filename
|
| 27 |
+
if not path.is_file():
|
| 28 |
+
raise RuntimeError("Model snapshot lacks required file: " + filename)
|
| 29 |
+
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
| 30 |
+
if digest != expected:
|
| 31 |
+
raise RuntimeError("Model source file SHA-256 mismatch: " + filename)
|
| 32 |
+
actual[filename] = digest
|
| 33 |
+
weights_sha = hashlib.sha256((model_path / "model.safetensors").read_bytes()).hexdigest()
|
| 34 |
+
if weights_sha != config["model"]["expected_weights_sha256"]:
|
| 35 |
+
raise RuntimeError("Weights SHA-256 differs from the documented inference snapshot")
|
| 36 |
+
actual["model.safetensors"] = weights_sha
|
| 37 |
+
return actual
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def task_loader_overrides(task):
|
| 41 |
+
kwargs = {"revision": task["dataset_revision"]}
|
| 42 |
+
storage = task.get("storage_adapter")
|
| 43 |
+
if storage:
|
| 44 |
+
if (set(storage) != {"dataset_name", "data_dir"}
|
| 45 |
+
or storage["dataset_name"] is not None
|
| 46 |
+
or storage["data_dir"] != task["dataset_name"]):
|
| 47 |
+
raise ValueError("Invalid ARC storage adapter")
|
| 48 |
+
return {"dataset_name": None}, {**kwargs, "data_dir": storage["data_dir"]}
|
| 49 |
+
return {}, kwargs
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def build_group(config):
|
| 53 |
+
members = []
|
| 54 |
+
for name, task in config["tasks"].items():
|
| 55 |
+
overrides, dataset_kwargs = task_loader_overrides(task)
|
| 56 |
+
member = {"task": name, "dataset_kwargs": dataset_kwargs}
|
| 57 |
+
member.update(overrides)
|
| 58 |
+
members.append(member)
|
| 59 |
+
return {"group": "purrence_pinned_evaluation", "task": members}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def verify_harness(config):
|
| 63 |
+
import importlib.metadata
|
| 64 |
+
from pathlib import Path
|
| 65 |
+
dist = importlib.metadata.distribution("lm_eval")
|
| 66 |
+
direct = json.loads(dist.read_text("direct_url.json") or "{}")
|
| 67 |
+
expected = config["harness"]["revision"]
|
| 68 |
+
if direct.get("vcs_info", {}).get("commit_id") != expected:
|
| 69 |
+
raise RuntimeError("lm_eval is not installed from the pinned source revision")
|
| 70 |
+
url = direct.get("url", "").removesuffix(".git")
|
| 71 |
+
if url != config["harness"]["repository"]:
|
| 72 |
+
raise RuntimeError("lm_eval source repository does not match the pinned config")
|
| 73 |
+
sources = {}
|
| 74 |
+
for name, relative in config["harness"]["task_configs"].items():
|
| 75 |
+
path = Path(dist.locate_file(relative))
|
| 76 |
+
if not path.is_file():
|
| 77 |
+
raise RuntimeError("Missing pinned task source: " + relative)
|
| 78 |
+
sources[name] = hashlib.sha256(path.read_bytes()).hexdigest()
|
| 79 |
+
return {"version": dist.version, "revision": expected, "repository": url,
|
| 80 |
+
"task_source_sha256": sources}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def load_tasks(config):
|
| 84 |
+
from lm_eval.tasks import TaskManager
|
| 85 |
+
manager = TaskManager()
|
| 86 |
+
tasks = manager.load(build_group(config))["tasks"]
|
| 87 |
+
for name, expected in config["tasks"].items():
|
| 88 |
+
task = tasks[name]
|
| 89 |
+
overrides, kwargs = task_loader_overrides(expected)
|
| 90 |
+
if task.get_config("dataset_path") != expected["dataset_path"]:
|
| 91 |
+
raise RuntimeError("Unexpected dataset path for " + name)
|
| 92 |
+
expected_name = overrides.get("dataset_name", expected["dataset_name"])
|
| 93 |
+
if task.get_config("dataset_name") != expected_name or task.get_config("dataset_kwargs") != kwargs:
|
| 94 |
+
raise RuntimeError("Dataset revision/config override failed for " + name)
|
| 95 |
+
if task.VERSION != expected["task_version"] or task.OUTPUT_TYPE != "multiple_choice":
|
| 96 |
+
raise RuntimeError("Unexpected task version or output type for " + name)
|
| 97 |
+
if not set(expected["metrics"]).issubset(task.aggregation()):
|
| 98 |
+
raise RuntimeError("Required metrics are unavailable for " + name)
|
| 99 |
+
split = task.get_config("test_split") or task.get_config("validation_split")
|
| 100 |
+
if split != expected["evaluation_split"] or len(task.eval_docs) != expected["examples"]:
|
| 101 |
+
raise RuntimeError("Evaluation split/count mismatch for " + name)
|
| 102 |
+
return manager, tasks
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def check_samples(results, config):
|
| 106 |
+
for name, task in config["tasks"].items():
|
| 107 |
+
samples = results.get("samples", {}).get(name, [])
|
| 108 |
+
counts = results.get("n-samples", {}).get(name, {})
|
| 109 |
+
n = task["examples"]
|
| 110 |
+
if counts.get("original") != n or counts.get("effective") != n or len(samples) != n:
|
| 111 |
+
raise RuntimeError("Full per-example output missing for " + name)
|
| 112 |
+
for sample in samples:
|
| 113 |
+
args = sample.get("arguments", [])
|
| 114 |
+
if not args or any(len(arg) != 2 or not all(isinstance(x, str) for x in arg) for arg in args):
|
| 115 |
+
raise RuntimeError("Rendered choice prompts missing for " + name)
|
| 116 |
+
if len(sample.get("resps", [])) != len(args) or len(sample.get("filtered_resps", [])) != len(args):
|
| 117 |
+
raise RuntimeError("Per-choice model outputs missing for " + name)
|
| 118 |
+
if not {"acc", "acc_norm"}.issubset(sample.get("metrics", [])):
|
| 119 |
+
raise RuntimeError("Per-example metrics missing for " + name)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def json_default(value):
|
| 123 |
+
if hasattr(value, "tolist"):
|
| 124 |
+
return value.tolist()
|
| 125 |
+
return str(value)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def reaggregate(results, arith, config):
|
| 129 |
+
summary = {}
|
| 130 |
+
for name, task in config["tasks"].items():
|
| 131 |
+
samples = results["samples"][name]
|
| 132 |
+
seen = set()
|
| 133 |
+
correct = {"acc": 0, "acc_norm": 0}
|
| 134 |
+
for sample in samples:
|
| 135 |
+
doc_id = sample["doc_id"]
|
| 136 |
+
if doc_id in seen:
|
| 137 |
+
raise RuntimeError("Duplicate doc_id in " + name)
|
| 138 |
+
seen.add(doc_id)
|
| 139 |
+
responses = [float(item[0]) for item in sample["filtered_resps"]]
|
| 140 |
+
if not responses or not all(math.isfinite(x) for x in responses):
|
| 141 |
+
raise RuntimeError("Invalid choice scores in " + name)
|
| 142 |
+
choices = (sample["doc"]["choices"]["text"] if name.startswith("arc_")
|
| 143 |
+
else sample["doc"]["choices"] if name == "hellaswag"
|
| 144 |
+
else [sample["doc"]["sol1"], sample["doc"]["sol2"]])
|
| 145 |
+
if len(choices) != len(responses) or any(sample["arguments"][i][1] != " " + choice
|
| 146 |
+
for i, choice in enumerate(choices)):
|
| 147 |
+
raise RuntimeError("Choice prompts do not match the task document in " + name)
|
| 148 |
+
target = int(sample["target"])
|
| 149 |
+
for metric, scores in (("acc", responses),
|
| 150 |
+
("acc_norm", [x / len(c) for x, c in zip(responses, choices)])):
|
| 151 |
+
prediction = max(range(len(scores)), key=scores.__getitem__)
|
| 152 |
+
if prediction == target:
|
| 153 |
+
correct[metric] += 1
|
| 154 |
+
if int(sample[metric]) != int(prediction == target):
|
| 155 |
+
raise RuntimeError("Logged per-example correctness mismatch in " + name)
|
| 156 |
+
summary[name] = {"examples": len(samples), **{m: c / len(samples) for m, c in correct.items()}}
|
| 157 |
+
for metric in correct:
|
| 158 |
+
if abs(summary[name][metric] - results["results"][name][metric + ",none"]) > 1e-12:
|
| 159 |
+
raise RuntimeError("Reaggregated metric differs from lm_eval in " + name)
|
| 160 |
+
|
| 161 |
+
rows = arith["results"]["arithmark-3"]["predictions"]
|
| 162 |
+
if len(rows) != config["arithmark3"]["examples"]:
|
| 163 |
+
raise RuntimeError("ArithMark did not preserve every prediction")
|
| 164 |
+
for metric, pred_key, score_key in (("acc", "raw_prediction", "raw_scores"),
|
| 165 |
+
("acc_norm", "normalized_prediction", "normalized_scores")):
|
| 166 |
+
if not all(all(math.isfinite(float(v)) for v in row[score_key]) for row in rows):
|
| 167 |
+
raise RuntimeError("ArithMark contains non-finite scores")
|
| 168 |
+
if not all(max(range(len(row[score_key])), key=row[score_key].__getitem__) == row[pred_key]
|
| 169 |
+
for row in rows):
|
| 170 |
+
raise RuntimeError("ArithMark saved prediction differs from scores")
|
| 171 |
+
count = len(rows)
|
| 172 |
+
summary["arithmark3"] = {"examples": count,
|
| 173 |
+
"acc": sum(row["raw_prediction"] == row["label"] for row in rows) / count,
|
| 174 |
+
"acc_norm": sum(row["normalized_prediction"] == row["label"] for row in rows) / count}
|
| 175 |
+
for metric in ("acc", "acc_norm"):
|
| 176 |
+
if abs(summary["arithmark3"][metric] - arith["results"]["arithmark-3"][metric] / 100) > 1e-12:
|
| 177 |
+
raise RuntimeError("ArithMark reaggregation differs from official script")
|
| 178 |
+
|
| 179 |
+
indices = {}
|
| 180 |
+
for metric in ("acc", "acc_norm"):
|
| 181 |
+
arc = (summary["arc_easy"][metric] + summary["arc_challenge"][metric]) / 2
|
| 182 |
+
indices[metric] = 100 * (((summary["hellaswag"][metric] - .25) / .75)
|
| 183 |
+
+ ((arc - .25) / .75) + ((summary["piqa"][metric] - .5) / .5)
|
| 184 |
+
+ .65 * ((summary["arithmark3"]["acc_norm"] - .25) / .75)) / 3.65
|
| 185 |
+
return {"metrics": summary, "intelligence_index": indices,
|
| 186 |
+
"examples_total": sum(item["examples"] for item in summary.values())}
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def main():
|
| 190 |
+
config, config_sha = read_config()
|
| 191 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 192 |
+
parser.add_argument("--model", default=config["model"]["default_local_path"],
|
| 193 |
+
help="Local model directory or Hugging Face model ID (default: current directory)")
|
| 194 |
+
parser.add_argument("--output", type=Path, required=True,
|
| 195 |
+
help="Directory for full per-example results and reaggregation")
|
| 196 |
+
parser.add_argument("--revision", default=None,
|
| 197 |
+
help="Hub model revision; defaults to the current main revision")
|
| 198 |
+
args = parser.parse_args()
|
| 199 |
+
if sys.version_info < (3, 10):
|
| 200 |
+
raise SystemExit("Python 3.10 or newer is required")
|
| 201 |
+
if args.output.exists() and any(args.output.iterdir()):
|
| 202 |
+
raise SystemExit("Output directory must be empty or absent: " + str(args.output))
|
| 203 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 204 |
+
|
| 205 |
+
os.environ.setdefault("HF_DATASETS_CACHE", str(args.output / "hf-cache" / "datasets"))
|
| 206 |
+
os.environ.setdefault("HF_HUB_CACHE", str(args.output / "hf-cache" / "hub"))
|
| 207 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 208 |
+
os.environ.setdefault("OMP_NUM_THREADS", "4")
|
| 209 |
+
|
| 210 |
+
import torch
|
| 211 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 212 |
+
from lm_eval import simple_evaluate
|
| 213 |
+
from lm_eval.models.huggingface import HFLM
|
| 214 |
+
|
| 215 |
+
torch.set_num_threads(min(4, torch.get_num_threads()))
|
| 216 |
+
torch.set_float32_matmul_precision("highest")
|
| 217 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 218 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 219 |
+
started = time.monotonic()
|
| 220 |
+
|
| 221 |
+
model_arg = Path(args.model).expanduser()
|
| 222 |
+
if model_arg.is_dir():
|
| 223 |
+
model_path = model_arg.resolve()
|
| 224 |
+
model_source = {"kind": "local", "path": str(model_path)}
|
| 225 |
+
else:
|
| 226 |
+
model_path = Path(snapshot_download(args.model, revision=args.revision))
|
| 227 |
+
model_revision = model_path.name
|
| 228 |
+
model_source = {"kind": "huggingface_hub", "repo_id": args.model, "revision": model_revision}
|
| 229 |
+
model_files = verify_model_files(model_path, config)
|
| 230 |
+
weights_sha = model_files["model.safetensors"]
|
| 231 |
+
|
| 232 |
+
harness = verify_harness(config)
|
| 233 |
+
manager, tasks = load_tasks(config)
|
| 234 |
+
cfg = config["model"]
|
| 235 |
+
lm = HFLM(pretrained=str(model_path), device=cfg["device"], dtype=cfg["dtype"],
|
| 236 |
+
trust_remote_code=cfg["trust_remote_code"], batch_size=cfg["batch_size"],
|
| 237 |
+
max_length=cfg["max_length"], add_bos_token=cfg["add_bos_token"])
|
| 238 |
+
result = simple_evaluate(model=lm, tasks=list(tasks.values()), task_manager=manager,
|
| 239 |
+
num_fewshot=config["evaluation"]["num_fewshot"], batch_size=cfg["batch_size"],
|
| 240 |
+
log_samples=config["evaluation"]["log_samples"], apply_chat_template=False,
|
| 241 |
+
system_instruction=None, limit=None, random_seed=17, numpy_random_seed=17,
|
| 242 |
+
torch_random_seed=17, fewshot_random_seed=17, bootstrap_iters=1000)
|
| 243 |
+
check_samples(result, config)
|
| 244 |
+
(args.output / "lm_eval_results.json").write_text(
|
| 245 |
+
json.dumps(result, indent=2, default=json_default) + "\n")
|
| 246 |
+
|
| 247 |
+
arith_cfg = config["arithmark3"]
|
| 248 |
+
script = hf_hub_download(arith_cfg["repository"], arith_cfg["script"],
|
| 249 |
+
revision=arith_cfg["revision"], repo_type="dataset")
|
| 250 |
+
dataset = hf_hub_download(arith_cfg["repository"], arith_cfg["dataset"],
|
| 251 |
+
revision=arith_cfg["revision"], repo_type="dataset")
|
| 252 |
+
arith_script_sha = hashlib.sha256(Path(script).read_bytes()).hexdigest()
|
| 253 |
+
if arith_script_sha != arith_cfg["script_sha256"]:
|
| 254 |
+
raise RuntimeError("Pinned ArithMark script SHA-256 mismatch")
|
| 255 |
+
arith_dir = args.output / "arithmark3"
|
| 256 |
+
arith_dir.mkdir()
|
| 257 |
+
old_argv = sys.argv
|
| 258 |
+
try:
|
| 259 |
+
sys.argv = [script, "--model", str(model_path), "--data-path", dataset,
|
| 260 |
+
"--device", "cpu", "--dtype", "float32", "--primary-metric", "acc_norm",
|
| 261 |
+
"--save-predictions", "--results-dir", str(arith_dir)]
|
| 262 |
+
runpy.run_path(script, run_name="__main__")
|
| 263 |
+
finally:
|
| 264 |
+
sys.argv = old_argv
|
| 265 |
+
arith_files = list(arith_dir.glob("*.json"))
|
| 266 |
+
if len(arith_files) != 1:
|
| 267 |
+
raise RuntimeError("Expected exactly one ArithMark output file")
|
| 268 |
+
arith = json.loads(arith_files[0].read_text())
|
| 269 |
+
expected_sha = hashlib.sha256(Path(dataset).read_bytes()).hexdigest()
|
| 270 |
+
if arith["dataset"]["sha256"] != expected_sha or len(arith["results"]["arithmark-3"]["predictions"]) != arith_cfg["examples"]:
|
| 271 |
+
raise RuntimeError("ArithMark dataset provenance or prediction count mismatch")
|
| 272 |
+
|
| 273 |
+
aggregate = reaggregate(result, arith, config)
|
| 274 |
+
report = {"passed": True, "protocol": config["protocol"], "model": model_source,
|
| 275 |
+
"model_weights_sha256": weights_sha, "model_files_sha256": model_files,
|
| 276 |
+
"runner_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
| 277 |
+
"config_sha256": config_sha,
|
| 278 |
+
"harness": harness, "evaluation_config_sha256": config_sha,
|
| 279 |
+
"arithmark3": {"repository": arith_cfg["repository"], "revision": arith_cfg["revision"],
|
| 280 |
+
"dataset_sha256": expected_sha,
|
| 281 |
+
"official_script": arith_cfg["script"],
|
| 282 |
+
"official_script_sha256": arith_script_sha},
|
| 283 |
+
"settings": {"device": "cpu", "dtype": "float32", "zero_shot": True,
|
| 284 |
+
"chat_template": False, "trust_remote_code": True, "tf32": False},
|
| 285 |
+
**aggregate, "elapsed_seconds": time.monotonic() - started,
|
| 286 |
+
"python": platform.python_version(), "torch": torch.__version__}
|
| 287 |
+
(args.output / "reaggregation.json").write_text(json.dumps(report, indent=2) + "\n")
|
| 288 |
+
print(json.dumps(report, indent=2))
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
main()
|
requirements-eval.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Run from the model directory so requirements.txt resolves beside this file.
|
| 2 |
+
-r requirements.txt
|
| 3 |
+
lm_eval @ git+https://github.com/EleutherAI/lm-evaluation-harness.git@d6de81643928d653435c431bae19945d41d32520
|
| 4 |
+
datasets==3.1.0
|
| 5 |
+
numpy==1.26.4
|
| 6 |
+
pyarrow==17.0.0
|
| 7 |
+
accelerate==0.34.2
|
| 8 |
+
huggingface_hub>=0.26,<1.0
|
| 9 |
+
tqdm>=4.66
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.10.0
|
| 2 |
+
tokenizers==0.20.3
|
| 3 |
+
safetensors==0.8.0
|
| 4 |
+
transformers==4.46.3
|
tokenization_purrence.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Transformers adapter preserving literal text and the original byte BPE."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from transformers import PreTrainedTokenizer
|
| 4 |
+
from .purrence_core import Sub3MTokenizer
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class PurrenceTokenizer(PreTrainedTokenizer):
|
| 8 |
+
vocab_files_names = {"vocab_file": "tokenizer/ordinary-tokenizer.json",
|
| 9 |
+
"artifact_file": "tokenizer/artifact.json"}
|
| 10 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 11 |
+
|
| 12 |
+
def __init__(self, vocab_file, artifact_file, **kwargs):
|
| 13 |
+
self.native = Sub3MTokenizer(Path(artifact_file).parent)
|
| 14 |
+
self.vocab_file = vocab_file
|
| 15 |
+
self.artifact_file = artifact_file
|
| 16 |
+
self.vocab = self.native.backend.get_vocab()
|
| 17 |
+
self.vocab["<|endoftext|>"] = 2047
|
| 18 |
+
self.reverse_vocab = {v: k for k, v in self.vocab.items()}
|
| 19 |
+
kwargs.setdefault("bos_token", "<|endoftext|>")
|
| 20 |
+
kwargs.setdefault("eos_token", "<|endoftext|>")
|
| 21 |
+
kwargs.setdefault("pad_token", "<|endoftext|>")
|
| 22 |
+
kwargs.setdefault("model_max_length", 8192)
|
| 23 |
+
kwargs["split_special_tokens"] = True
|
| 24 |
+
kwargs["clean_up_tokenization_spaces"] = False
|
| 25 |
+
super().__init__(**kwargs)
|
| 26 |
+
|
| 27 |
+
@property
|
| 28 |
+
def vocab_size(self):
|
| 29 |
+
return 2048
|
| 30 |
+
|
| 31 |
+
def get_vocab(self):
|
| 32 |
+
return dict(self.vocab)
|
| 33 |
+
|
| 34 |
+
def _tokenize(self, text, **kwargs):
|
| 35 |
+
return [self.reverse_vocab[i] for i in self.native.encode(text)]
|
| 36 |
+
|
| 37 |
+
def _convert_token_to_id(self, token):
|
| 38 |
+
return self.vocab[token]
|
| 39 |
+
|
| 40 |
+
def _convert_id_to_token(self, index):
|
| 41 |
+
return self.reverse_vocab[index]
|
| 42 |
+
|
| 43 |
+
def convert_tokens_to_string(self, tokens):
|
| 44 |
+
return self.native.decode([self.vocab[t] for t in tokens])
|
| 45 |
+
|
| 46 |
+
def _decode(self, token_ids, skip_special_tokens=False, **kwargs):
|
| 47 |
+
if isinstance(token_ids, int):
|
| 48 |
+
token_ids = [token_ids]
|
| 49 |
+
return self.native.decode([int(i) for i in token_ids], skip_boundaries=skip_special_tokens)
|
| 50 |
+
|
| 51 |
+
def save_vocabulary(self, save_directory, filename_prefix=None):
|
| 52 |
+
import shutil
|
| 53 |
+
if filename_prefix:
|
| 54 |
+
raise ValueError("This fixed tokenizer uses canonical filenames")
|
| 55 |
+
target = Path(save_directory) / "tokenizer"
|
| 56 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
paths = []
|
| 58 |
+
for source in [self.vocab_file, self.artifact_file]:
|
| 59 |
+
dest = target / Path(source).name
|
| 60 |
+
if Path(source).resolve() != dest.resolve():
|
| 61 |
+
shutil.copyfile(source, dest)
|
| 62 |
+
paths.append(str(dest))
|
| 63 |
+
return tuple(paths)
|
tokenizer/artifact.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_sha256": "fc240b741112488b639a711f502305601e3b8a1b01c5ae93a48b9ae55692dd33",
|
| 3 |
+
"tokenizers_version": "0.20.3",
|
| 4 |
+
"vocab_size": 2048,
|
| 5 |
+
"boundary_special": {
|
| 6 |
+
"id": 2047,
|
| 7 |
+
"purpose": "structurally injected document boundary",
|
| 8 |
+
"spelling": "<|endoftext|>"
|
| 9 |
+
}
|
| 10 |
+
}
|
tokenizer/ordinary-tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PurrenceTokenizer",
|
| 3 |
+
"auto_map": {"AutoTokenizer": ["tokenization_purrence.PurrenceTokenizer", null]},
|
| 4 |
+
"model_max_length": 8192,
|
| 5 |
+
"bos_token": "<|endoftext|>",
|
| 6 |
+
"eos_token": "<|endoftext|>",
|
| 7 |
+
"pad_token": "<|endoftext|>",
|
| 8 |
+
"clean_up_tokenization_spaces": false,
|
| 9 |
+
"split_special_tokens": true
|
| 10 |
+
}
|