API Reference¶
The complete public API, generated from the source docstrings.
Everything below is importable from the top-level kamui package.
Configuration & Model¶
kamui.model.config.ModelConfig
dataclass
¶
Configuration class for the KAMUI transformer model.
Holds all hyperparameters, performs validation, computes helper dimensions, and estimates the parameter count under explicit architectural assumptions.
Attributes:
| Name | Type | Description |
|---|---|---|
n_layers |
int
|
Number of transformer blocks. |
d_model |
int
|
Residual stream / embedding dimension. |
n_heads |
int
|
Number of attention heads. |
d_ff |
int
|
Feed-forward network hidden layer dimension. |
vocab_size |
int
|
Size of the token vocabulary. |
context_length |
int
|
Maximum sequence length. |
positional_encoding |
str
|
Type of positional encoding ('learned' or 'sinusoidal'). |
dropout |
float
|
Dropout rate (must be in [0, 1]). |
Source code in kamui/model/config.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
d_head
property
¶
Dimension of each attention head.
Calculated as d_model // n_heads.
attention_parameters
property
¶
Estimates total attention parameters across all layers.
Assumptions
- Multi-head causal self-attention is applied at each of the
n_layers. - In each layer, the input (residual stream of shape d_model) is projected to Query, Key, and Value spaces. Each of these 3 projections is a linear layer of shape (d_model, d_model) with a bias vector of shape (d_model).
- The output of the combined heads is projected back to the residual stream using an output projection of shape (d_model, d_model) with a bias of shape (d_model).
- Formula: n_layers * 4 * d_model * (d_model + 1)
feedforward_parameters
property
¶
Estimates total feed-forward network parameters across all layers.
Assumptions
- A position-wise MLP is applied at each of the
n_layers. - The MLP consists of two linear layers:
- Expansion layer: weight of shape (d_model, d_ff) and bias (d_ff).
- Projection layer: weight of shape (d_ff, d_model) and bias (d_model).
- Formula: n_layers * (2 * d_model * d_ff + d_model + d_ff)
embedding_parameters
property
¶
Estimates total embedding parameters.
Assumptions
- Token embedding matrix of shape (vocab_size, d_model).
- If
positional_encodingis "learned", a learned positional embedding matrix of shape (context_length, d_model) is present. - If
positional_encodingis "sinusoidal", positional encodings are fixed and add 0 trainable parameters. - Formula: (vocab_size * d_model) + (context_length * d_model if learned else 0)
estimated_total_parameters
property
¶
Estimates the total trainable parameter count of the model.
Assumptions
- Includes attention, feedforward, and embedding parameters.
- Includes normalization layer parameters:
- 2 LayerNorms per block (attention input, FFN input). Each LayerNorm has learnable scale (gamma) and bias (beta) parameters of shape (d_model,).
- 1 final LayerNorm before unembedding, also with scale and bias (d_model,).
- LayerNorm parameters formula: n_layers * 4 * d_model + 2 * d_model.
- Includes unembedding layer parameters:
- The weight matrix is tied to the token embedding matrix transpose, so it adds 0 trainable parameters.
- The unembedding linear layer has NO learnable bias (bias=False), matching standard GPT-2 weight-tying conventions.
__post_init__()
¶
Enforces tensor dimension and hyperparameter sanity checks.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any validation rule is violated. |
Source code in kamui/model/config.py
__repr__()
¶
Returns a helpful, formatted string representation of the model configuration.
Source code in kamui/model/config.py
from_yaml(path)
classmethod
¶
Loads a ModelConfig from a YAML file.
The YAML file must contain a 'model' section.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the YAML file. |
required |
Returns:
| Type | Description |
|---|---|
ModelConfig
|
An instance of ModelConfig. |
Source code in kamui/model/config.py
to_yaml(path)
¶
Serializes the ModelConfig instance to a YAML file.
If the file already exists, preserves other sections (e.g., 'training', 'data', 'logging') and only updates the 'model' block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path where the YAML file should be written. |
required |
Source code in kamui/model/config.py
kamui.model.transformer.KAMUITransformer
¶
Bases: Module
The full decoder-only transformer language model.
Assembles the embedding, a stack of n_layers transformer blocks, a
final LayerNorm, and a weight-tied linear unembedding. Given token IDs
it returns next-token logits; given targets as well it returns the
cross-entropy loss.
Attributes:
| Name | Type | Description |
|---|---|---|
embed |
Combined token + positional embedding. |
|
blocks |
|
|
final_ln |
LayerNorm applied before the unembedding. |
|
unembed |
Linear |
Source code in kamui/model/transformer.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | |
__init__(config)
¶
Construct the model from a configuration and initialise weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ModelConfig
|
The model configuration. |
required |
Source code in kamui/model/transformer.py
from_config(config)
classmethod
¶
from_yaml(path)
classmethod
¶
Load a ModelConfig from YAML and construct the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to a YAML file with a |
required |
Source code in kamui/model/transformer.py
forward(token_ids, targets=None)
¶
Run the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_ids
|
Tensor
|
Integer tensor of shape |
required |
targets
|
Tensor | None
|
Optional next-token labels of shape |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Logits of shape |
Tensor
|
otherwise the scalar cross-entropy loss. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Source code in kamui/model/transformer.py
num_parameters(trainable_only=True)
¶
Return the number of parameters.
nn.Module.parameters() already yields each shared (weight-tied)
parameter once, so the tied embedding/unembedding matrix is counted
a single time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trainable_only
|
bool
|
If True (default), count only parameters with
|
True
|
Returns:
| Type | Description |
|---|---|
int
|
The parameter count. |
Source code in kamui/model/transformer.py
Tokenizer¶
kamui.tokenizer.bpe.BPETokenizer
¶
Byte-pair encoding tokeniser, trained and applied from scratch.
The vocabulary is structured as follows
- IDs 0–255: raw byte tokens (
\x00…\xff). - IDs 256 … 256+len(special_tokens)-1: special tokens in declaration order.
- IDs 256+len(special_tokens) … vocab_size-1: merged subword tokens, one per BPE merge rule, in the order they were learned.
Special tokens are injected into the id→bytes mapping as unique sentinel byte-sequences that can never arise from UTF-8 text, so they cannot accidentally appear inside a regular token.
Attributes:
| Name | Type | Description |
|---|---|---|
vocab_size |
int
|
Total number of tokens (bytes + specials + merges). |
special_tokens |
tuple[str, ...]
|
Tuple of registered special token strings. |
Source code in kamui/tokenizer/bpe.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | |
vocab_size
property
¶
Total number of tokens in the vocabulary.
special_tokens
property
¶
Tuple of registered special token strings, in ID order.
__init__(merges, vocab, special_tokens=_DEFAULT_SPECIAL_TOKENS)
¶
Internal constructor. Use train or load instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
merges
|
list[tuple[int, int]]
|
Ordered list of (left_id, right_id) merge rules. |
required |
vocab
|
dict[int, bytes]
|
Mapping from integer ID to raw bytes representation. |
required |
special_tokens
|
tuple[str, ...]
|
Tuple of special token strings in ID order. |
_DEFAULT_SPECIAL_TOKENS
|
Source code in kamui/tokenizer/bpe.py
train(corpus, vocab_size, special_tokens=_DEFAULT_SPECIAL_TOKENS, verbose=False)
classmethod
¶
Train a BPE tokenizer on a text corpus.
The training procedure:
1. Read the full corpus as a UTF-8 string.
2. Encode every character as its raw UTF-8 bytes (256 base tokens).
3. Reserve IDs for special tokens immediately after the 256 byte tokens.
4. Iteratively find the most-frequent adjacent pair of IDs across the
entire corpus, assign it a new merged ID, and update the corpus.
Repeat until vocab_size is reached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
str | Path
|
Path to the training corpus text file, or a raw string corpus (if the value does not correspond to an existing file, it is treated as the corpus text directly — useful for tests). |
required |
vocab_size
|
int
|
Target vocabulary size. Must be ≥ 256 + len(special_tokens). |
required |
special_tokens
|
tuple[str, ...]
|
Special tokens to reserve, in ID order. Defaults to
|
_DEFAULT_SPECIAL_TOKENS
|
verbose
|
bool
|
If True, print progress every 100 merges. |
False
|
Returns:
| Type | Description |
|---|---|
BPETokenizer
|
A trained |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
FileNotFoundError
|
If |
Source code in kamui/tokenizer/bpe.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
encode(text)
¶
Encode a string into a list of token IDs.
Special tokens in the text are matched first (as whole strings) before the remainder is byte-encoded and merged. Merge rules are applied greedily, left to right, until no more merges are possible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Any Unicode string. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
A list of integer token IDs, possibly empty for an empty input. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in kamui/tokenizer/bpe.py
decode(ids)
¶
Decode a list of token IDs back to a string.
The decode is lossless for any sequence produced by encode:
decode(encode(text)) == text for all Unicode strings.
Special-token IDs are decoded back to their string representation
(e.g. token 256 → "<|endoftext|>").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ids
|
list[int]
|
A list of integer token IDs. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The decoded string. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If any ID is outside [0, vocab_size). |
Source code in kamui/tokenizer/bpe.py
save(path)
¶
Save the tokenizer to a JSON file.
The JSON contains:
- "special_tokens": list of special token strings in ID order.
- "merges": list of [left_id, right_id] pairs in training order.
- "vocab": dict mapping string token ID → base64-encoded bytes
representation of the token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the output JSON file. Parent directories are created if they do not exist. |
required |
Raises:
| Type | Description |
|---|---|
IOError
|
If writing fails. |
Source code in kamui/tokenizer/bpe.py
load(path)
classmethod
¶
Load a tokenizer from a JSON file created by save.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the JSON file. |
required |
Returns:
| Type | Description |
|---|---|
BPETokenizer
|
A |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
ValueError
|
If the JSON structure is invalid. |
IOError
|
If reading fails. |
Source code in kamui/tokenizer/bpe.py
token_to_id(token)
¶
Return the integer ID for a special token string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
A special token string (must be in |
required |
Returns:
| Type | Description |
|---|---|
int
|
The integer ID. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the token is not a registered special token. |
Source code in kamui/tokenizer/bpe.py
kamui.tokenizer.vocab.Vocabulary
¶
Vocabulary management for the KAMUI BPE tokenizer.
Maintains bidirectional mapping between string tokens and integer IDs, ensuring deterministic ID assignment, duplicate prevention, and stable serialization.
Source code in kamui/tokenizer/vocab.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | |
vocab_size
property
¶
Return the total number of tokens in the vocabulary.
special_tokens
property
¶
Return a copy of the set of registered special tokens.
__init__(special_tokens=None)
¶
Initialise a new Vocabulary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
special_tokens
|
Iterable[str] | None
|
Optional iterable of special tokens. If None,
defaults to (" |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If empty strings are provided as special tokens, or if there are duplicate special tokens. |
TypeError
|
If special tokens contains non-string elements. |
Source code in kamui/tokenizer/vocab.py
add_token(token)
¶
Add a token to the vocabulary and return its assigned integer ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The string token to add. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The newly assigned integer ID of the token. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the token is empty, already exists, or is a duplicate special token. |
TypeError
|
If the token is not a string. |
Source code in kamui/tokenizer/vocab.py
add_tokens(tokens)
¶
Add multiple tokens to the vocabulary.
This operation is atomic. If any token in the input iterable is invalid (e.g., empty or duplicate), no tokens will be added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Iterable[str]
|
Iterable of string tokens to add. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any token is empty, already exists in the vocabulary, or is a duplicate within the input iterable. |
TypeError
|
If any token is not a string. |
Source code in kamui/tokenizer/vocab.py
token_to_id(token)
¶
Look up the integer ID of a string token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The string token to look up. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The integer ID. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the token is not in the vocabulary. |
TypeError
|
If the token is not a string. |
Source code in kamui/tokenizer/vocab.py
id_to_token(token_id)
¶
Look up the string representation of a token ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_id
|
int
|
The integer ID to look up. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The string token. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the token ID is out of range. |
TypeError
|
If the token ID is not an integer. |
Source code in kamui/tokenizer/vocab.py
__getitem__(key)
¶
Look up a token string to get its ID, or a token ID to get its string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str | int
|
Either a string token or an integer token ID. |
required |
Returns:
| Type | Description |
|---|---|
int | str
|
Integer ID if key is a string, or string token if key is an integer. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a string key is not found. |
ValueError
|
If an integer key is out of range. |
TypeError
|
If key is neither a string nor an integer. |
Source code in kamui/tokenizer/vocab.py
__contains__(item)
¶
Check if a token or ID is in the vocabulary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
str | int
|
Either a string token or an integer token ID. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the token or ID exists in the vocabulary, False otherwise. |
Source code in kamui/tokenizer/vocab.py
contains(token)
¶
Return True if token is present in the vocabulary.
This is the named method form of token in vocabulary. It only
accepts string tokens; use the in operator to check by integer ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The string token to look up. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the token exists in the vocabulary, False otherwise. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If token is not a string. |
Source code in kamui/tokenizer/vocab.py
__len__()
¶
__repr__()
¶
Return a human-readable summary of the vocabulary.
Source code in kamui/tokenizer/vocab.py
save(path)
¶
Save the vocabulary to a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the target JSON file. |
required |
Raises:
| Type | Description |
|---|---|
IOError
|
If writing to the file fails. |
Source code in kamui/tokenizer/vocab.py
load(path)
classmethod
¶
Load a vocabulary from a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the JSON file to load. |
required |
Returns:
| Type | Description |
|---|---|
Vocabulary
|
A new Vocabulary instance reconstructed from the file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the JSON format is invalid, IDs are not consecutive starting from 0, or special tokens are invalid or missing. |
FileNotFoundError
|
If the vocabulary file does not exist. |
IOError
|
If reading the file fails. |
Source code in kamui/tokenizer/vocab.py
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | |
Training¶
kamui.training.trainer.TrainingConfig
dataclass
¶
All training hyperparameters.
Attributes:
| Name | Type | Description |
|---|---|---|
max_lr |
/ min_lr
|
Peak / floor learning rates for the schedule. |
warmup_steps |
int
|
Linear-warmup steps. |
max_steps |
int
|
Cosine-decay horizon (LR floors after this). |
grad_accum_steps |
int
|
Micro-batches accumulated per optimiser update. |
max_grad_norm |
float
|
Gradient-clipping norm (<= 0 disables clipping). |
weight_decay |
float
|
AdamW weight decay for weight matrices. |
betas |
/ eps
|
AdamW hyperparameters. |
eval_interval |
int
|
Steps between validation evaluations (0 disables). |
log |
bool
|
Whether to print structured log lines. |
Source code in kamui/training/trainer.py
kamui.training.trainer.Trainer
¶
An explicit training loop over a KAMUITransformer.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
The model being trained. |
|
optimizer |
AdamW with decayed / non-decayed parameter groups. |
|
scheduler |
The cosine-with-warmup LR schedule. |
|
step |
The global optimiser-step counter. |
|
history |
list[dict[str, float]]
|
A list of per-step log dicts (step, train_loss, lr, grad_norm). |
Source code in kamui/training/trainer.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
__init__(model, train_loader, val_loader=None, config=None)
¶
Create a trainer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The model to train. |
required |
train_loader
|
Iterable[Batch]
|
An iterable of |
required |
val_loader
|
Iterable[Batch] | None
|
Optional iterable for validation. |
None
|
config
|
TrainingConfig | None
|
Training hyperparameters (defaults used if None). |
None
|
Source code in kamui/training/trainer.py
train(n_steps)
¶
Run n_steps optimiser updates.
Each update accumulates grad_accum_steps micro-batches, clips the
gradient, applies the scheduled LR, and steps the optimiser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_steps
|
int
|
Number of optimiser updates to run. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, float]]
|
The list of per-step log dicts recorded during this call. |
Source code in kamui/training/trainer.py
evaluate()
¶
Return the mean validation loss over val_loader.
Returns:
| Type | Description |
|---|---|
float
|
The token-weighted mean cross-entropy loss. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no validation loader was provided, or it is empty. |
Source code in kamui/training/trainer.py
Hooks¶
kamui.hooks.manager.HookManager
¶
Context-managed activation capture over a model's named submodules.
Source code in kamui/hooks/manager.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | |
__init__(model)
¶
Create a hook manager for model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The model to attach hooks to. Must expose a |
required |
Source code in kamui/hooks/manager.py
attach(module_path, point)
¶
Attach a capture hook at "<module_path>.<point>".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module_path
|
str
|
A |
required |
point
|
str
|
One of |
required |
Returns:
| Type | Description |
|---|---|
HookManager
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the resulting hook point is not valid for this model. |
Source code in kamui/hooks/manager.py
get(hook_point)
¶
Return a cached activation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_point
|
str
|
The full hook-point string, e.g. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
The captured tensor. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If nothing is cached at |
Source code in kamui/hooks/manager.py
get_all()
¶
clear()
¶
remove()
¶
Remove all hooks and restore any wrapped forwards.
The activation cache is left intact so captured tensors remain
accessible after the with block exits.
Source code in kamui/hooks/manager.py
kamui.hooks.registry.HookRegistry
¶
Canonical registry of valid hook points for a KAMUITransformer.
Source code in kamui/hooks/registry.py
all_points(config)
classmethod
¶
Return every valid hook point string for config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ModelConfig
|
The model configuration (only |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
An ordered list of hook-point strings: the embedding output, the |
list[str]
|
per-layer attention/FFN points for each of |
list[str]
|
the unembedding input. |
Source code in kamui/hooks/registry.py
validate(hook_point, config)
classmethod
¶
Return True if hook_point is valid for config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_point
|
str
|
A candidate hook-point string. |
required |
config
|
ModelConfig
|
The model configuration. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Whether |
Source code in kamui/hooks/registry.py
Interpretability Tools¶
kamui.mechinterp.attention_viz.AttentionVisualizer
¶
Extract every head's attention pattern for a given input.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
A trained |
|
tokenizer |
A tokenizer with |
Source code in kamui/mechinterp/attention_viz.py
__init__(model, tokenizer)
¶
Create a visualizer over model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
KAMUITransformer
|
A |
required |
tokenizer
|
Any
|
A tokenizer with |
required |
Source code in kamui/mechinterp/attention_viz.py
run(token_ids)
¶
Capture all attention weights for a single sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_ids
|
Tensor
|
Token IDs of shape |
required |
Returns:
| Type | Description |
|---|---|
AttentionResult
|
An |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in kamui/mechinterp/attention_viz.py
kamui.mechinterp.logit_lens.LogitLens
¶
Project the residual stream to vocabulary at every layer.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
A trained |
|
tokenizer |
A tokenizer with |
Source code in kamui/mechinterp/logit_lens.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
__init__(model, tokenizer)
¶
Create a logit lens over model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
KAMUITransformer
|
A |
required |
tokenizer
|
Any
|
A tokenizer with a |
required |
Source code in kamui/mechinterp/logit_lens.py
run(token_ids, top_k=5)
¶
Run the logit lens over a single sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_ids
|
Tensor
|
Token IDs of shape |
required |
top_k
|
int
|
Number of top tokens to record per (layer, position). |
5
|
Returns:
| Type | Description |
|---|---|
LogitLensResult
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in kamui/mechinterp/logit_lens.py
kamui.mechinterp.probing.LinearProbe
¶
Train linear classifiers on cached activations.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
A trained |
Source code in kamui/mechinterp/probing.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
__init__(model)
¶
Create a prober over model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
KAMUITransformer
|
A |
required |
train(hook_point, dataset, labels, epochs=200, lr=0.05, seed=0)
¶
Train one probe on activations captured at hook_point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook_point
|
str
|
A registry hook point (e.g. |
required |
dataset
|
list[Tensor]
|
One 1-D token-ID tensor per example. |
required |
labels
|
list[int]
|
One integer class label per example. |
required |
epochs
|
int
|
Full-batch gradient steps for the probe. |
200
|
lr
|
float
|
Probe learning rate. |
0.05
|
seed
|
int
|
RNG seed for probe init. |
0
|
Returns:
| Type | Description |
|---|---|
ProbeResult
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset/labels are empty, mismatched, or contain fewer than 2 classes. |
Source code in kamui/mechinterp/probing.py
probe_all_layers(dataset, labels, epochs=200, lr=0.05, seed=0)
¶
Train one probe on the residual stream at every depth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
list[Tensor]
|
One 1-D token-ID tensor per example. |
required |
labels
|
list[int]
|
One integer class label per example. |
required |
epochs
|
int
|
Full-batch gradient steps per probe. |
200
|
lr
|
float
|
Probe learning rate. |
0.05
|
seed
|
int
|
RNG seed for probe init. |
0
|
Returns:
| Type | Description |
|---|---|
LayerProbeResult
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset/labels are invalid. |
Source code in kamui/mechinterp/probing.py
kamui.mechinterp.activation_patch.ActivationPatcher
¶
Causal localisation via activation patching.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
A trained |
Source code in kamui/mechinterp/activation_patch.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
__init__(model)
¶
Create a patcher over model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
KAMUITransformer
|
A |
required |
patch_single(clean_ids, corrupted_ids, hook_point, answer_token=None, corrupt_token=None)
¶
Patch a single output hook point and return the recovery.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clean_ids
|
Tensor
|
Clean token IDs |
required |
corrupted_ids
|
Tensor
|
Corrupted token IDs of the same shape. |
required |
hook_point
|
str
|
A patchable output point: |
required |
answer_token
|
int | None
|
Optional metric answer token (defaults to the clean run's top prediction). |
None
|
corrupt_token
|
int | None
|
Optional metric corrupt token (defaults to the corrupted run's top prediction). |
None
|
Returns:
| Type | Description |
|---|---|
float
|
The logit-difference recovery in roughly |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes differ or |
Source code in kamui/mechinterp/activation_patch.py
patch_all_layers(clean_ids, corrupted_ids, component='attn', answer_token=None, corrupt_token=None)
¶
Patch each layer's attn or ffn output, one at a time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clean_ids
|
Tensor
|
Clean token IDs. |
required |
corrupted_ids
|
Tensor
|
Corrupted token IDs of the same shape. |
required |
component
|
str
|
|
'attn'
|
answer_token
|
int | None
|
Optional metric answer token. |
None
|
corrupt_token
|
int | None
|
Optional metric corrupt token. |
None
|
Returns:
| Type | Description |
|---|---|
PatchingResult
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in kamui/mechinterp/activation_patch.py
patch_all_heads(clean_ids, corrupted_ids, answer_token=None, corrupt_token=None)
¶
Patch each attention head's contribution, one at a time.
A head is patched by replacing its slice of the out_proj input (the
concatenated per-head outputs) with the clean run's slice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clean_ids
|
Tensor
|
Clean token IDs. |
required |
corrupted_ids
|
Tensor
|
Corrupted token IDs of the same shape. |
required |
answer_token
|
int | None
|
Optional metric answer token. |
None
|
corrupt_token
|
int | None
|
Optional metric corrupt token. |
None
|
Returns:
| Type | Description |
|---|---|
HeadPatchingResult
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes differ. |
Source code in kamui/mechinterp/activation_patch.py
kamui.mechinterp.induction.InductionHeadDetector
¶
Score and causally test every attention head for induction behaviour.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
A trained |
Source code in kamui/mechinterp/induction.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
__init__(model)
¶
Create a detector over model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
KAMUITransformer
|
A |
required |
score_all_heads(prefix_len=None, n_samples=4, seed=0)
¶
Compute the induction score for every (layer, head) pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix_len
|
int | None
|
Length of the repeated prefix (defaults to
|
None
|
n_samples
|
int
|
Number of random repeated sequences to average over. |
4
|
seed
|
int
|
Base RNG seed (sample |
0
|
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], float]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in kamui/mechinterp/induction.py
plot_scores(scores, figsize=None)
¶
Heatmap of induction scores by (layer, head).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
dict[tuple[int, int], float]
|
The dict returned by |
required |
figsize
|
tuple[float, float] | None
|
Optional figure size. |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
The matplotlib |
Source code in kamui/mechinterp/induction.py
ablate_and_measure(heads, prefix_len=None, seed=0)
¶
Zero-ablate heads and measure the rise in in-context loss.
In-context performance is the mean next-token loss over the second half of a repeated random sequence (predictable purely from context). A positive return value means ablation hurt in-context learning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
heads
|
list[tuple[int, int]]
|
|
required |
prefix_len
|
int | None
|
Repeated-prefix length (defaults to |
None
|
seed
|
int
|
RNG seed for the sequence. |
0
|
Returns:
| Type | Description |
|---|---|
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in kamui/mechinterp/induction.py
kamui.mechinterp.circuits.CircuitAblator
¶
Zero- and mean-ablation of model components.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
A trained |
Source code in kamui/mechinterp/circuits.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
__init__(model)
¶
Create an ablator over model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
KAMUITransformer
|
A |
required |
ablate(components, token_ids, metric)
¶
Zero-ablate components and measure the metric change.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
list[str]
|
Output hook points to ablate
( |
required |
token_ids
|
Tensor
|
Input token IDs |
required |
metric
|
Metric
|
Maps logits to a scalar (higher = better). |
required |
Returns:
| Type | Description |
|---|---|
AblationResult
|
An |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in kamui/mechinterp/circuits.py
mean_ablate(components, token_ids, baseline_ids, metric)
¶
Replace components' activations with their baseline-batch means.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
list[str]
|
Output hook points to ablate. |
required |
token_ids
|
Tensor
|
Task input |
required |
baseline_ids
|
Tensor
|
Baseline batch |
required |
metric
|
Metric
|
Maps logits to a scalar (higher = better). |
required |
Returns:
| Type | Description |
|---|---|
AblationResult
|
An |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in kamui/mechinterp/circuits.py
Evaluation¶
kamui.evaluate.perplexity.compute_perplexity(model, dataloader)
¶
Compute token-level perplexity over a dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
KAMUITransformer
|
A |
required |
dataloader
|
Iterable[tuple[Tensor, Tensor] | Tensor]
|
An iterable of batches. Each batch is either a
|
required |
Returns:
| Type | Description |
|---|---|
float
|
The corpus perplexity as a float. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataloader yields no tokens. |
Source code in kamui/evaluate/perplexity.py
kamui.evaluate.generation.generate(model, tokenizer, prompt, max_new_tokens=50, strategy='greedy', temperature=1.0, top_k=50, top_p=0.9, seed=None)
¶
Generate a continuation of prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
KAMUITransformer
|
A |
required |
tokenizer
|
TokenizerLike
|
An object with |
required |
prompt
|
str
|
The (non-empty) prompt string. |
required |
max_new_tokens
|
int
|
Number of tokens to generate. |
50
|
strategy
|
str
|
|
'greedy'
|
temperature
|
float
|
Logit temperature (> 0), applied before filtering. |
1.0
|
top_k
|
int
|
k for |
50
|
top_p
|
float
|
p for |
0.9
|
seed
|
int | None
|
Optional RNG seed for reproducible sampling. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The full decoded string (prompt + continuation). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in kamui/evaluate/generation.py
kamui.evaluate.calibration.expected_calibration_error(probs, labels, n_bins=15)
¶
Compute the expected calibration error of top-1 predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probs
|
Tensor
|
|
required |
labels
|
Tensor
|
|
required |
n_bins
|
int
|
Number of equal-width confidence bins. |
15
|
Returns:
| Type | Description |
|---|---|
float
|
The ECE in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes are inconsistent or |