forked from thinking-machines-lab/tinker-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllms-full.txt
More file actions
2564 lines (1791 loc) · 108 KB
/
llms-full.txt
File metadata and controls
2564 lines (1791 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# TINKER DOCUMENTATION
This file contains the complete Tinker documentation and SDK reference.
## Table of Contents
1. Documentation (MDX files)
2. Type Definitions (from tinker.types)
---
# PART 1: DOCUMENTATION
## File: index.mdx
# Tinker: a training API for researchers and developers
Tinker lets you focus on what matters in LLM fine-tuning – your data and algorithms – while we handle the heavy lifting of distributed training.
You write a simple loop that runs on your CPU-only machine, including the data or environment and the loss function. We figure out how to make the training work on a bunch of GPUs, doing the exact computation you specified, efficiently. To change the model you're working with, you only need to change a single string in your code.
Tinker gives you full control over the training loop and all the algorithmic details. It's not a magic black box that makes fine-tuning "easy". It's a clean abstraction that shields you from the complexity of distributed training while preserving your control.
Here's how the division of responsibilities works in practice:
| **You focus on** | **You write** | **We handle** |
|---|---|---|
| 📊 **Datasets and RL environments**<br />Your custom training data | 💻 **Simple Python script**<br />Runs on your CPU | ⚡ **Efficient distributed training of large models**<br />Llama, Qwen, and more |
| 🎯 **Training logic**<br />Your loss functions, training loop, and evals | 🔧 **API calls**<br />`forward_backward()`<br />`optim_step()`<br />`sample()` | 🛡️ **Reliability**<br />Hardware failures handled transparently |
## Features
What the Tinker service currently supports:
- Tinker lets you fine-tune open-weight models like the Qwen and Llama series, including large mixture-of-experts models like Qwen3-235B-A22B.
- Tinker implements low-rank adaptation (LoRA) fine-tuning, not full fine-tuning. However, we believe that LoRA gives the same performance as full fine-tuning for many important use cases, especially in RL (see [LoRA Without Regret](https://thinkingmachines.ai/blog/lora/)).
- You can download the weights of your trained model to use outside of Tinker, for example with your inference provider of choice.
## A quick look at functionality
Tinker's main functionality is contained in a few key functions:
- `forward_backward`: feed in your data and loss function, and we'll compute and accumulate the gradients for you.
- `optim_step`: update your model using the accumulated gradients
- `sample`: Generate outputs from your trained model
- other functions for saving and loading weights and optimizer state
## What's next?
Some features we expect to support in the future:
- Image input for applicable models
- Full fine-tuning
---
## File: losses.mdx
# Loss functions in Tinker
For most use cases, you can use the Tinker API's built-in loss functions by passing in a string identifier to `forward_backward`, which supports cross entropy and policy gradient objectives. When you need more control, `forward_backward_custom` enables arbitrary differentiable loss functions at the cost of an additional forward pass; we explain both approaches in this doc.
When you call `forward_backward`, you specify a loss function using a string that selects from a predetermined set of options, comprising the most common losses used for language model training.
- **Input:** `forward_backward` expects a certain set of input tensors, passed in via `datum.loss_fn_inputs`, which is a dict mapping `str` to either a numpy or torch tensor
- **Output:** `forward_backward` returns a `ForwardBackwardOutput`, which has a set of output tensors in `fwd_bwd_result.loss_fn_outputs`
For an example of using `forward_backward`, see `rl/train.py` in the Cookbook:
```python
async def forward_backward(
training_client: tinker.TrainingClient,
batch_d: List[tinker.Datum],
) -> List[torch.Tensor]:
"""Accumulate gradients on a minibatch of data"""
fwd_bwd_future = await training_client.forward_backward_async(
list(map(remove_mask, batch_d)), loss_fn="importance_sampling"
)
fwd_bwd_result = await fwd_bwd_future.result_async()
# Extract training logprobs from loss_fn_outputs
training_logprobs_D: list[torch.Tensor] = []
for output in fwd_bwd_result.loss_fn_outputs:
training_logprobs = output["logprobs"].to_torch()
training_logprobs_D.append(training_logprobs)
return training_logprobs_D
```
## Basic loss functions
Currently, the Tinker API supports `cross_entropy` (for supervised learning), `importance_sampling` (for RL), and `ppo` (for RL).
All tensors below have shape `(N,)` where `N` is `model_input.length`. They can be provided as `numpy.ndarray` or `torch.Tensor`, and the return values will use the same tensor type.
### Supervised learning: `cross_entropy`
For SL, we implement the standard cross-entropy loss (i.e., negative-log-likelihood), which optimizes the policy $p_\theta$ to maximize the log-probability of the tokens $x$:
$$
\mathcal{L(\theta)} = -\mathbb{E}_x[\log p_\theta(x)]
$$
In practice, this looks like `-(weights * logp(target_tokens)).sum()`, where `weights` is either 0 or 1, typically generated from `renderers.build_supervised_example` (i.e., to specify the desired assistant turns to train on).
- **Input tensors:**
- `target_tokens: array[(N,), int]` - Target token IDs
- `weights: array[(N,), float]` - Token-level loss weights (typically from the renderer)
- **Output tensors:**
- `logprobs: array[(N,), float]` - Log probabilities of predicted tokens
- **Output diagnostics:**
- `loss:sum` (scalar) - Sum of weighted cross-entropy losses
### Policy gradient: `importance_sampling`
For RL, we implement a common variant of the policy gradient objective, used in practical settings where the *learner policy* $p$ may differ from the *sampling policy* $q$, which is common due to e.g. [non-determinism](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/). To remove the bias caused by this difference, we can use a modified "importance sampling" objective:
$$
\nabla \mathbb{E}_{x\sim p_\theta}\bigl[r(x) \bigr] = \mathbb{E}_{x\sim q}\Bigl[r(x) \cdot \frac{\nabla p_\theta(x)}{q(x)}\Bigr]
$$
which yields the correct expected reward in expectation. This is implemented as `(exp(new_logprobs - logprobs) * advantages).sum()`, where `advantages` may additionally subtract a baseline from the rewards. Note this only works in the bandit setting, which is common in both RLHF and RLVR setups.
- **Input tensors:**
- `target_tokens: array[(N,), int]` - Target token IDs (from the sampler $q$)
- `logprobs: array[(N,), float]` - Reference log probabilities $q$ for the target tokens
- `advantages: array[(N,), float]` - Advantage values for RL
- **Output tensors:**
- `logprobs: array[(N,), float]` - Log probabilities $p$ for the target tokens
- **Output diagnostics:**
- `loss:sum` (scalar) - Sum of importance-weighted policy gradient losses
**Addendum:** Let's consider naively applying the policy gradient objective when $q \neq p$:
$$
\begin{align*}
\mathbb{E}_{x\sim q}\bigr[ r(x) \cdot \nabla \log p_\theta(x) \bigl] &= \sum_x q(x) r(x) \cdot \nabla \log p_\theta(x) \\
&= \sum_x q(x) (r(x) - \bar{r}) \nabla \log p_\theta(x) + \sum_x q(x) \bar{r} \cdot \nabla \log p_\theta(x) \\
&= \mathbb{E}_{x\sim q}\bigl[(r(x) - \bar{r}) \nabla \log p_\theta(x)\bigr] - \bar{r} \cdot \nabla KL(q \Vert p)
\end{align*}
$$
where $\bar{r} = \sum_x q(x) r(x)$, effectively an average-reward baseline.
- The first expectation term resembles a pseudo-policy gradient, increasing the log-likelihood of tokens $x$ which achieve higher-than-average rewards. (It is not an actual policy gradient, because $q \neq p$.)
- The second KL term is effectively a bias term which can destablize RL optimization. This bias increases as either the divergence $KL(q \Vert p)$ grows, or as the average reward $\bar{r}$ shifts.
## Flexible loss functions: `forward_backward_custom`
For use-cases outside of the above, we've provided the more flexible (but slower) methods `forward_backward_custom` and `forward_backward_custom_async` to compute a more general class of loss functions.
### Usage
Here's a simple example of a custom loss function:
```python
def logprob_squared_loss(data: list[Datum], logprobs: list[torch.Tensor]) -> tuple[torch.Tensor, dict[str, float]]:
loss = (logprobs ** 2).sum()
return loss, {"logprob_squared_loss": loss.item()}
```
You can call this loss function with `forward_backward_custom` like:
```python
loss, metrics = training_client.forward_backward_custom(data, logprob_squared_loss)
```
You can also define loss functions which operate on multiple sequences at a time. For example, (although practically useless), a loss function that computes the variance across the sequences can be implemented as:
```python
def variance_loss(data: list[Datum], logprobs: list[torch.Tensor]) -> tuple[torch.Tensor, dict[str, float]]:
flat_logprobs = torch.cat(logprobs)
variance = torch.var(flat_logprobs)
return variance, {"variance_loss": variance.item()}
```
A more practical use case would be to compute a Bradley-Terry loss on pairwise comparison data -- a classic approach in RL from human feedback, as introduced/popularized by [Learning to Summarize](https://arxiv.org/abs/2009.01325). Similarly, we can also implement [Direct Preference Optimization](https://arxiv.org/abs/2305.18290), which also computes a loss involving pairs of sequences; see the [DPO guide](/preferences/dpo-guide) for more details.
If you're using a custom loss function that you think is generally useful, please let us know, and we'll add it to the list of built-in loss functions.
We detail the `async` version of methods in the [Async and Futures](./async) of these docs.
### How `forward_backward_custom` works
---
## File: supervised-learning.mdx
import { CookbookLink } from '../components/CookbookLink'
# Supervised learning
In general, supervised learning means learning an input-output mapping from labeled data. In the context of this documentation, it'll mean that we're minimizing a weighted cross-entropy loss on token sequences, i.e., maximizing the log-probability of the specififed target tokens.
There are a few ways that supervised learning (abbreviated as SL) is commonly used in LLM fine-tuning pipelines:
- *Instruction tuning*: as the first step in post-training pipelines, applied to the *base model*, i.e., *raw pretrained model*. Typically, we do SL on a high-quality dataset that demonstrates the correct format and style, while boosting the model's skills of reasoning and instruction-following.
- *Context distillation* / *prompt distillation*: let's say we have a generic model that can do chat / instruction following / reasoning, but we want to adjust how it behaves in a certain scenario. We can add some instructions to the system message of our model. However, the system message might grow impractically long and start ignoring some of its instructions. So it's often better to create a supervised dataset on a narrow prompt distribution, with a shorter set of instructions that that are targeted at these prompts.
We'll cover these use cases in the documentation and cookbook code.
The library code implementing supervised learning can be found in the <CookbookLink path="tinker_cookbook/supervised">`supervised`</CookbookLink> directory.
---
## File: preferences.mdx
# Preferences
This overview page will cover learning from preferences.
*This is a placeholder page that needs to be written.*
---
## File: lora-primer.mdx
# LoRA Primer
Tinker supports [LoRA fine-tuning](https://arxiv.org/abs/2106.09685), which adjusts a small number of parameters, rather than full fine-tuning, which adjusts all of the parameters of the original model. Our current understanding is that LoRA has equivalent performance to full fine-tuning when doing RL or doing SL on small datasets, while it has worse performance on larger datasets. In more detail:
- For supervised fine-tuning on a small dataset, with fewer completion tokens than the number of LoRA parameters, then LoRA gives roughly the same performance as full fine-tuning.
- For supervised fine-tuning on a large dataset (like continued pre-training, or datasets with billions of tokens), LoRA will significantly underperform full fine-tuning.
- For reinforcement learning fine-tuning, LoRA performs roughly the same as full fine-tuning.
- While it has deficits when fine-tuning on larger datasets, LoRA may also typically better preserves the capabilities of the base model, according to [this study](https://arxiv.org/abs/2405.09673).
See the Connectionism blog post on [LoRA Without Regret](https://thinkingmachines.ai/blog/lora/) for more details and experimental results.
# Hyperparameters
The learning rate (LR) is usually the most important hyperparameter in your ML experiments. LoRA requires a much larger LR than full fine-tuning -- this is a mistkae people often make when porting their code to use LoRA, leading them to conclude that LoRA works poorly. Depending on the model size, the LoRA learning rate might be 20-100 times larger than the full fine-tuning learning rate.
We've provided a utility that calculates the factor you should scale the full fine-tuning LR by to get the equivalent LoRA LR.
```python
from tinker_cookbook.hyperparam_utils import get_lora_lr_over_full_finetune_lr
model_name = "meta-llama/Llama-3.1-8B"
print(get_lora_lr_over_full_finetune_lr(model_name))
```
Note that for `Llama-3.2-1B`, the factor is 32, while for `Llama-3.1-70B`, the factor is 128.
# What is LoRA exactly?
LoRA is short for Low-Rank Adaptation. Given that the original model has a weight matrix $W$, we replace it with a new weight matrix $W'=W + BA$, where $B$ and $A$ are low-rank matrices. If $W$ is an $n \times n$ matrix, then $B$ and $A$ are $n \times r$ and $r \times n$ matrices, respectively, where $r$ is the rank of the low-rank approximation. The default $r$ used by tinker is $32$.
The fact that LoRA uses a low-rank approximation of weight matrices is not terribly important -- we prefer to think of LoRA as just a random projection of the parameter space that happens to be efficient to implement. When training with RL or small SL datasets, we are only learning a small amount of information, and this reduced set of parameters is more than enough.
# What rank to use?
The default rank used by tinker is $32$. However, if you're doing SL on a large dataset, you should use a larger rank. The largest rank currently supported is $128$, so you should use this rank if you are doing SL on a large dataset. Supporting ranks $512$ and higher is on the roadmap.
For supervised learning, as a very rough approximation, LoRA will give good results as long as the number of LoRA parameters is at least as large as the number of completion tokens (i.e., weight=1 tokens). You can calculate the number of LoRA parameters with the following utility:
```python
from tinker_cookbook.hyperparam_utils import get_lora_param_count
model_name = "meta-llama/Llama-3.1-8B"
print(get_lora_param_count(model_name, lora_rank=32))
```
For reinforcement learning, we've found that small ranks give equivalent performance to larger ranks and full fine-tuning.
Note that conveniently, the optimal learning rate does *not* depend on the LoRA rank. In fact, you can verify that if you train with SL on different ranks (but with the same LR), you'll get exactly the same learning curves for the first few steps of training.
---
## File: evals.mdx
import { Callout } from 'nextra/components'
import { CookbookLink } from '../components/CookbookLink'
# Evaluations
Our training scripts will print out training and test loss. Two common workflows for evaluations are to do inline evals during training and to do offline evals on various checkpoints from a run.
## Inline Evals
You can add inline evaluations to your training runs by configuring evaluator builders in advance for both supervised fine-tuning and RL training jobs.
### Supervised Fine-Tuning (`supervised.train`)
Add one or both of the following to your config:
- **`evaluator_builders: list[EvaluatorBuilder]`** - Runs evaluations every `eval_every` steps
- **`infrequent_evaluator_builders: list[EvaluatorBuilder]`** - Runs evaluations every `infrequent_eval_every` steps
### RL Training (`rl.train`)
Add the following to your config:
- **`evaluator_builders: list[SamplingClientEvaluator]`** - Runs evaluations every `eval_every` steps
For implementation guidance and a detailed example, see <CookbookLink path="tinker_cookbook/eval/evaluators.py">here</CookbookLink> and
<CookbookLink path="tinker_cookbook/eval/inspect_evaluators.py">here</CookbookLink> respectively.
## Offline evals
We support and recommend several ways for creating and running your offline evaluations on your model checkpoints.
### Running Standard Evaluations with Inspect AI.
We support running many of the standard cited evaluations using the [Inspect AI library](https://github.com/UKGovernmentBEIS/inspect_ai).
We have provided a <CookbookLink path="tinker_cookbook/eval/run_inspect_evals.py">script</CookbookLink> to evaluate models using Tinker's internal sampling functionality as shown below.
```bash
MODEL_PATH=tinker://FIXME # YOUR MODEL PATH HERE
python -m tinker_cookbook.eval.run_inspect_evals \
model_path=$MODEL_PATH \
model_name=MODEL_NAME \ # YOUR MODEL_NAME HERE
tasks=inspect_evals/ifeval,inspect_evals/mmlu_0_shot \
renderer_name=RENDERER_NAME # YOUR RENDERER_NAME HERE
```
Click [here](https://github.com/UKGovernmentBEIS/inspect_ai/blob/main/docs/evals/listing.yml) to view additional supported evaluations.
### Creating your own Sampling Evaluations
We recommend two ways to create your own evaluations:
- creating your own tasks with Inspect AI and running like above
- creating your own SamplingClientEvaluator
#### Create tasks with Inspect AI
In addition to passing in standard evaluations, you can create your own tasks using inspect ai as detailed [here](https://inspect.aisi.org.uk/tasks.html).
Here is a toy example of how to create an evaluation with an LLM-as-a-judge where we use a model produced by tinker as a grader.
```python
import tinker
from inspect_ai import Task, task
from inspect_ai.dataset import MemoryDataset, Sample
from inspect_ai.model import GenerateConfig as InspectAIGenerateConfig
from inspect_ai.model import Model as InspectAIModel
from inspect_ai.scorer import model_graded_qa
from inspect_ai.solver import generate
from tinker_cookbook.eval.inspect_utils import InspectAPIFromTinkerSampling
QA_DATASET = MemoryDataset(
name="qa_dataset",
samples=[
Sample(
input="What is the capital of France?",
target="Paris",
),
Sample(
input="What is the capital of Italy?",
target="Rome",
),
],
)
service_client = tinker.ServiceClient()
sampling_client = service_client.create_sampling_client(
base_model="meta-llama/Llama-3.1-8B-Instruct"
)
api = InspectAPIFromTinkerSampling(
renderer_name="llama3",
model_name="meta-llama/Llama-3.1-8B-Instruct",
sampling_client=sampling_client,
verbose=False,
)
GRADER_MODEL = InspectAIModel(api=api, config=InspectAIGenerateConfig())
@task
def example_lm_as_judge() -> Task:
"""
Example task using LLM-as-a-judge scoring.
Note: The grader model defaults to the model being evaluated.
To use a different grader model, specify it with --model-grader when using inspect directly.
"""
return Task(
name="llm_as_judge",
dataset=QA_DATASET,
solver=generate(),
scorer=model_graded_qa(
instructions="Grade strictly against the target text as general answer key and rubric. "
"Respond 'GRADE: C' if correct or 'GRADE: I' otherwise.",
partial_credit=False,
# model parameter is optional - if not specified, uses the model being evaluated
model=GRADER_MODEL,
),
)
```
Inspect also natively supports replacing our `GRADER_MODEL` with any openai-chat-completion style api (e.g. openrouter).
#### Create your own SamplingClientEvaluator
Alternatively, you can create your own SamplingClientEvaluator class instead of using Inspect AI. This is a lower
level abstraction than the above with finer-grain control over running your evaluations.
We expose this to interace to allow users more control over their datasets and metrics. To illustrate, see this
<CookbookLink path="tinker_cookbook/eval/custom_evaluators.py">custom evaluators</CookbookLink> example of how one might create their own complex SamplingClientEvaluator.
For a more illustrative toy instructive example see below.
```python
from typing import Any, Callable
import tinker
from tinker import types
from tinker_cookbook import renderers
from tinker_cookbook.evaluators import SamplingClientEvaluator
from tinker_cookbook.tokenizer_utils import get_tokenizer
class CustomEvaluator(SamplingClientEvaluator):
"""
A toy SamplingClientEvaluator that runs a custom evaluation and returns its metrics.
"""
def __init__(
self,
dataset: Any,
grader_fn: Callable[[str, str], bool],
model_name: str,
renderer_name: str,
):
"""
Initialize the CustomEvaluator.
Args:
config: Configuration object containing all evaluation parameters
"""
self.dataset = dataset
self.grader_fn = grader_fn
tokenizer = get_tokenizer(model_name)
self.renderer = renderers.get_renderer(name=renderer_name, tokenizer=tokenizer)
async def __call__(self, sampling_client: tinker.SamplingClient) -> dict[str, float]:
"""
Run custom evaluation on the given sampling client and return metrics.
Args:
sampling_client: The sampling client to evaluate
Returns:
Dictionary of metrics from inspect evaluation
"""
metrics = {}
num_examples = len(self.dataset)
num_correct = 0
sampling_params = types.SamplingParams(
max_tokens=100,
temperature=0.7,
top_p=1.0,
stop=self.renderer.get_stop_sequences(),
)
for datum in self.dataset:
model_input: types.ModelInput = self.renderer.build_generation_prompt(
[renderers.Message(role="user", content=datum["input"])]
)
# Generate response
r: types.SampleResponse = await sampling_client.sample_async(
prompt=model_input, num_samples=1, sampling_params=sampling_params
)
tokens: list[int] = r.sequences[0].tokens
response: renderers.Message = self.renderer.parse_response(tokens)[0]
if self.grader_fn(response["content"], datum["output"]):
num_correct += 1
metrics["accuracy"] = num_correct / num_examples
return metrics
```
Here is an example of how we can use the above CustomEvaluator on a toy dataset and grader.
```python
QA_DATASET = [
{"input": "What is the capital of France?", "output": "Paris"},
{"input": "What is the capital of Germany?", "output": "Berlin"},
{"input": "What is the capital of Italy?", "output": "Rome"},
]
def grader_fn(response: str, target: str) -> bool:
return target.lower() in response.lower()
evaluator = CustomEvaluator(
dataset=QA_DATASET,
grader_fn=grader_fn,
renderer_name="llama3",
model_name="meta-llama/Llama-3.1-8B-Instruct",
)
service_client = tinker.ServiceClient()
sampling_client = service_client.create_sampling_client(base_model="meta-llama/Llama-3.1-8B-Instruct")
async def main():
result = await evaluator(sampling_client)
print(result)
asyncio.run(main())
```
---
## File: dev-tips.mdx
# Developer Tips
## AI-assisted development
We've provided a single-file version of the documentation that can be fed to LLMs for development: see [llms.txt](/llms.txt) and [llms-full.txt](/llms-full.txt).
---
## File: async.mdx
# Async and Futures
## Sync and Async APIs
Every method in the Tinker Python library has both a synchronous (sync) and an asynchronous (async) version. The async variants end with `_async`:
| **Client** | **Sync method** | **Async method** |
|---|---|---|
| `ServiceClient` | `create_lora_training_client()` | `create_lora_training_client_async()` |
| `TrainingClient` | `forward()` | `forward_async()` |
| `SamplingClient` | `sample()` | `sample_async()` |
| `RestClient` | `list_training_run_ids()` | `list_training_run_ids_async()` |
Tinker's `async` functionality requires an `asyncio` event loop, which you typically run like `asyncio.run(main())`.
**When to use each:**
- **Async:** Best for high-performance workflows where you need concurrency, especially when waiting on multiple network calls.
- **Sync:** Simpler for scripts and learning examples. Easier to reason about but blocks on each operation.
The Tinker Cookbook generally uses `async` for implementations where performance is critical and sync for pedagogical examples.
## Understanding Futures
Most Tinker API methods are **non-blocking**, but may take a little while to run. They return immediately with a `Future` object that acknowledges that your request has been submitted. To get the actual result, you must explicitly wait:
**Sync Python:**
```python
result = client.forward_backward_async(data, loss_fn)
result = result.result_async() # Blocks until complete
```
**Async Python (note the double await):**
```python
result = await client.forward_backward_async(data, loss_fn)
result = await result.result_async()
```
After the first `await`, you're guaranteed that the request has been submitted, which ensures that it'll be ordered correctly relative to other requests. The second `await` waits for the actual computation to finish and returns the numerical outputs. For operations like `forward_backward`, the second `await` also guarantees that operation has been applied to the model---for `forward_backward`, this means that the gradients have been accumulated in the model's optimizer state.
## Performance tips: overlap requests
For best performance, you should aim to submit your next request while the current one is running. Doing so is more important with Tinker than with other training systems because Tinker training runs on discrete [clock cycles](./under-the-hood#clock-cycles) (~10 seconds each). If you don't have a request queued when a cycle starts, you'll miss that cycle entirely.
**Example pattern for overlapping requests:**
```python
# Submit first request
future1 = await client.forward_backward_async(batch1, loss_fn)
# Submit second request immediately (don't wait for first to finish)
future2 = await client.forward_backward_async(batch2, loss_fn)
# Now retrieve results
result1 = await future1.result_async()
result2 = await future2.result_async()
```
---
## File: overview-building.mdx
# Overview (Tinker Cookbook)
The next sections provide a variety of guides for how to use the Tinker API for research and applications.
We expect people to use Tinker in a few different ways:
1. You want to define datasets and environments and plug them into existing training code from the Tinker Cookbook.
2. You want to write your own training loops from scratch, starting with the basics.
3. You want to understand the classes and other concepts in Tinker Cookbook so you can extend them to add new functionality.
Different parts of the docs will be tailored to these different approaches.
We'll start with a couple of general pages that'll be relevant to almost all of the use cases:
- [Rendering to Tokens](./rendering.mdx) -- how we convert from a conversation data structure to a list of tokens (a.k.a. chat templates).
- [LoRA Primer](./lora-primer.mdx) -- basic background of LoRA, and how to choose hyperparameters. For most fine-tuning applications, LoRA will give results that are roughly the same as full fine-tuning, however, you need to use different learning rates.
---
## File: save-load.mdx
# Saving and loading weights and optimizer state
During training, you'll need to save checkpoints for two main purposes: *sampling* (to test your model) and *resuming training* (to continue from where you left off). The `TrainingClient` provides three methods to handle these cases:
1. `save_weights_for_sampler()`: saves a copy of the model weights that can be used for sampling.
2. `save_state()`: saves the weights and the optimizer state. You can fully resume training from this checkpoint.
3. `load_state()`: load the weights and the optimizer state. You can fully resume training from this checkpoint.
Note that (1) is faster and requires less storage space than (2).
Both `save_*` functions require a `name` parameter---a string that you can set to identify the checkpoint within the current training run. For example, you can name your checkpoints `"0000"`, `"0001"`, `"step_1000"`, etc.
The return value contains a `path` field, which is a fully-qualified path, which will look something like `tinker://<model_id>/<name>`. This path is persistent and can be loaded later by a new `ServiceClient` or `TrainingClient`.
### Example: Saving for sampling
```python
# Setup
import tinker
service_client = tinker.ServiceClient()
training_client = service_client.create_lora_training_client(
base_model="meta-llama/Llama-3.2-1B", rank=32
)
# Save a checkpoint that you can use for sampling
sampling_path = training_client.save_weights_for_sampler(name="0000").result().path
# Create a sampling client with that checkpoint
sampling_client = service_client.create_sampling_client(model_path=sampling_path) #
```
**Shortcut:** Combine these steps with:
```python
sampling_client = training_client.save_weights_and_get_sampling_client(name="0000")
```
### Example: Saving to resume training
Use `save_state()` and `load_state()` when you need to pause and continue training with full optimizer state preferred:
```python
# Save a checkpoint that you can resume from
resume_path = training_client.save_state(name="0010").result().path
# Load that checkpoint
training_client.load_state(resume_path)
```
### When to use `save_state()` and `load_state()`:
- Multi-step training pipelines (e.g. supervised learning followed by reinforcement learning)
- Adjusting hyperparameters or data mid-run
- Recovery from interruptions or failures
- Any scenario where you need to preserve exact optimizer state (momentum, learning rate schedules, etc.)
---
## File: training-sampling.mdx
import { Callout } from 'nextra/components'
# Getting started with training and sampling
In this guide, we'll step you through using the Tinker Python library to do the basic operations needed for training and sampling.
[View the complete Python script →](/quickstart.py.txt)
## Creating the training client
The main object we'll be using is the `TrainingClient`, which corresponds to a fine-tuned model that we can train and sample from.
First, set your Tinker API key environment variable. In the terminal where you'll run Python, or in your `.bashrc`, put `export TINKER_API_KEY=<your key>`.
Then, create a `ServiceInterface`. This lets you find out what base models are available to be fine-tuned.
```python
import tinker
service_client = tinker.ServiceClient()
print("Available models:")
for item in service_client.get_server_capabilities().supported_models:
print("- " + item.model_name)
```
You'll see a list of model names:
```
- meta-llama/Llama-3.1-70B
- meta-llama/Llama-3.1-8B
...
- Qwen/Qwen3-235B-A22B-Instruct-2507
- Qwen/Qwen3-30B-A3B-Base
```
We currently support models from the Qwen3 and Llama3 series. We're going to use Qwen3-30B-A3B-Base (a raw pre-trained model) for these examples. See [Available Models in Tinker](/model-lineup) for the full list.
Now we can create the `TrainingClient`:
```python
base_model = "Qwen/Qwen3-30B-A3B-Base"
training_client = service_client.create_lora_training_client(
base_model=base_model
)
```
Note that we've specified a *base model*, which is the model we'll initialize from. In this case, it's a raw pre-trained model, but most of the "base models" in Tinker are fine-tuned for chat/instruction-following. You should check the details of the model you're using in their system cards.
## Preparing the training data
Now we can do training updates on the model. This quickstart example won't show best practices for LLM fine-tuning; it's just an API demo. Check out [Rendering](/rendering), [Supervised Fine-tuning](/supervised-learning) and the other Cookbook examples for guidance on how to use Tinker in real applications.
For this model, we'll train a model that can translate words into Pig Latin. The rules for Pig Latin are simple:
- If a word begins with a consonant, move it to the end and add "ay"
- If a word begins with a vowel, just add "way" to the end
Here are some example completions we'd like the model to perform, where the prompt is in green and the model's completion is in red:
<div className="example">
<span className="prompt">English: hello world<br/>
Pig Latin: </span><span className="completion">ello-hay orld-way</span>
</div>
Let's create some training examples and convert them to a format expected by Tinker.
```python
# Create some training examples
examples = [
{
"input": "banana split",
"output": "anana-bay plit-say"
},
{
"input": "quantum physics",
"output": "uantum-qay ysics-phay"
},
{
"input": "donut shop",
"output": "onut-day op-shay"
},
{
"input": "pickle jar",
"output": "ickle-pay ar-jay"
},
{
"input": "space exploration",
"output": "ace-spay exploration-way"
},
{
"input": "rubber duck",
"output": "ubber-ray uck-day"
},
{
"input": "coding wizard",
"output": "oding-cay izard-way"
},
]
# Convert examples into the format expected by the training client
from tinker import types
# Get the tokenizer from the training client
tokenizer = training_client.get_tokenizer()
def process_example(example: dict, tokenizer) -> types.Datum:
# Format the input with Input/Output template
# For most real use cases, you'll want to use a renderer / chat template,
# (see later docs) but here, we'll keep it simple.
prompt = f"English: {example['input']}\nPig Latin:"
prompt_tokens = tokenizer.encode(prompt, add_special_tokens=True)
prompt_weights = [0] * len(prompt_tokens)
# Add a space before the output string, and finish with double newline
completion_tokens = tokenizer.encode(f" {example['output']}\n\n", add_special_tokens=False)
completion_weights = [1] * len(completion_tokens)
tokens = prompt_tokens + completion_tokens
weights = prompt_weights + completion_weights
input_tokens = tokens[:-1]
target_tokens = tokens[1:] # We're predicting the next token, so targets need to be shifted.
weights = weights[1:]
# A datum is a single training example for the loss function.
# It has model_input, which is the input sequence that'll be passed into the LLM,
# loss_fn_inputs, which is a dictionary of extra inputs used by the loss function.
return types.Datum(
model_input=types.ModelInput.from_ints(tokens=input_tokens),
loss_fn_inputs=dict(weights=weights, target_tokens=target_tokens)
)
processed_examples = [process_example(ex, tokenizer) for ex in examples]
# Visualize the first example for debugging purposes
datum0 = processed_examples[0]
print(f"{'Input':<20} {'Target':<20} {'Weight':<10}")
print("-" * 50)
for i, (inp, tgt, wgt) in enumerate(zip(datum0.model_input.to_ints(), datum0.loss_fn_inputs['target_tokens'].tolist(), datum0.loss_fn_inputs['weights'].tolist())):
print(f"{repr(tokenizer.decode([inp])):<20} {repr(tokenizer.decode([tgt])):<20} {wgt:<10}")
```
The visualization of the first example is:
```
Input Target Weight
--------------------------------------------------
'English' ':' 0.0
':' ' I' 0.0
' I' ' love' 0.0
' love' ' tink' 0.0
' tink' 'ering' 0.0
'ering' '\n' 0.0
'\n' 'P' 0.0
'P' 'ig' 0.0
'ig' ' Latin' 0.0
' Latin' ':' 0.0
':' ' I' 1.0
' I' '-way' 1.0
'-way' ' o' 1.0
' o' 've' 1.0
've' '-l' 1.0
'-l' 'ay' 1.0
'ay' ' ink' 1.0
' ink' 'ering' 1.0
'ering' '-t' 1.0
'-t' 'ay' 1.0
'ay' '<|endoftext|>' 1.0
```
## Performing a training update
Now we can use this data to perform a training update. We'll do 6 updates on the same batch of data. (Note that this is not typically a good way to train!)
```python
import numpy as np
for _ in range(6):
fwdbwd_future = training_client.forward_backward(processed_examples, "cross_entropy")
optim_future = training_client.optim_step(types.AdamParams(learning_rate=1e-4))
# Wait for the results
fwdbwd_result = fwdbwd_future.result()
optim_result = optim_future.result()
# fwdbwd_result contains the logprobs of all the tokens we put in. Now we can compute the weighted
# average log loss per token.
logprobs = np.concatenate([output['logprobs'].tolist() for output in fwdbwd_result.loss_fn_outputs])
weights = np.concatenate([example.loss_fn_inputs['weights'].tolist() for example in processed_examples])
print(f"Loss per token: {-np.dot(logprobs, weights) / weights.sum():.4f}")
```
Note that the `forward_backward` and `optim_step` functions immediately return *futures*, which acknowledge that the task has been queued up by the server. For improved speed, we submitted both operations before waiting for the result by calling `result()` on the futures.
## Sampling from the model
Now we can test our model by sampling from it. In this case, we'll translate the phrase "coffee break" into Pig Latin.
```python
# First, create a sampling client. We need to transfer weights
sampling_client = training_client.save_weights_and_get_sampling_client(name='pig-latin-model')
# Now, we can sample from the model.
prompt=types.ModelInput.from_ints(tokenizer.encode("English: coffee break\nPig Latin:"))
params = types.SamplingParams(max_tokens=20, temperature=0.0, stop=["\n"]) # Greedy sampling
future = sampling_client.sample(prompt=prompt, sampling_params=params, num_samples=8)
result = future.result()
print("Responses:")
for i, seq in enumerate(result.sequences):
print(f"{i}: {repr(tokenizer.decode(seq.tokens))}")
```
Since sampling is nondeterministic (sadly, even with temperature=0.0, [due to batching](https://thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference/)), the output will be different each time. You should see something like this:
```
Responses:
0: ' offe-bay eak-bay\n\n'
1: ' offey-coy eak-bray\n\n'
2: ' offecay eakbray\n\n'
3: ' offeec-cay eak-brcay\n\n\n'
4: ' offecay akebay\n\n'
5: ' offee-Cay ake-bay\n\n\n'
6: ' offey-pay eak-bray\n\n'
7: ' offee – cay eak – bray\n\n'
```
---
## File: rendering.mdx
import { CookbookLink } from '../components/CookbookLink'
# Rendering
Rendering is the process of converting list-of-message datatypes into their token representations and is roughly the same as [chat templates](https://huggingface.co/docs/transformers/en/chat_templating); however, the chat template functionality in other libraries is only well-suited for inference, whereas this library provides a more complete interface that handles supervised and reinforcement learning.
## Renderer Class
The Renderer class is the main interface used for rendering and can be found in <CookbookLink path="tinker_cookbook/renderers.py">`renderers.py`</CookbookLink>.
Let's use the following working example of a conversation between a user and an assistant.
```python
messages =[
{'role': 'system', 'content': 'Answer concisely; at most one sentence per response'},
{'role': 'user', 'content': 'What is the longest-lived rodent species?'},
{'role': 'assistant', 'content': 'The naked mole rat, which can live over 30 years.'},
{'role': 'user', 'content': 'How do they live so long?'},
{'role': 'assistant', 'content': 'They evolved multiple protective mechanisms including special hyaluronic acid that prevents cancer, extremely stable proteins, and efficient DNA repair systems that work together to prevent aging.'}
]
```
## Generating messages
Our model maps tokens to tokens, but with the renderer, it can map messages to messages. To sample messages from the model, we need to use three methods from the renderer:
- `build_generation_prompt`
- `get_stop_sequences`
- `parse_response`
`build_generation_prompt` converts a conversation into a prompt that we can use to sample from the assistant. This is used during reinforcement learning and at deployment time.
Let's remove the last assistant message and call `build_generation_prompt` to get a prompt that we can use to sample an alternative response from the assistant.
```python
from tinker_cookbook import renderers, tokenizer_utils
tokenizer = tokenizer_utils.get_tokenizer('Qwen/Qwen3-30B-A3B')
renderer = renderers.get_renderer('qwen3', tokenizer)
prompt = renderer.build_generation_prompt(messages[:-1])
print(prompt)
print('-'*10)
print(tokenizer.decode(prompt.to_ints()))
```
First you can see that the prompt is a `ModelInput` object, which is a list of `EncodedTextChunk` objects (but contains different objects in multi-modal data).
```
ModelInput(chunks=[EncodedTextChunk(tokens=[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 8948, 198, 16141, 3529, 285, 974, 26, 518, 1429, 825, 11652, 817, 2033, 151645, 198, 151644, 872, 198, 3838, 374, 279, 22032, 61854, 20589, 306, 9419, 30, 151645, 198, 151644, 77091, 198, 785, 19020, 34651, 11244, 11, 892, 646, 3887, 916, 220, 18, 15, 1635, 13, 151645, 198, 151644, 872, 198, 10234, 30, 151645, 198, 151644, 77091, 198], type='encoded_text')])
----------
<|im_start|>system
Answer concisely; at most one sentence per response<|im_end|>
<|im_start|>user
What is the longest-lived rodent species?<|im_end|>
<|im_start|>assistant
The naked mole rat, which can live over 30 years.<|im_end|>
<|im_start|>user
How do they live so long?<|im_end|>
<|im_start|>assistant
```
Given that we're providing messages as input, we probably want a message output, rather than a token output. For that, we can use `parse_response`.
```python
import tinker
from tinker.types import SamplingParams
service_client = tinker.ServiceClient()
sampling_client = service_client.create_sampling_client(base_model='Qwen/Qwen3-30B-A3B')
stop_sequences = renderer.get_stop_sequences()
print(f"Stop sequences: {stop_sequences}")
sampling_params = SamplingParams(max_tokens=100, temperature=0.5, stop=stop_sequences)
output = sampling_client.sample(prompt, sampling_params=sampling_params, num_samples=1).result()
print(f"Sampled tokens: {output.sequences[0].tokens}")
sampled_message, parse_success = renderer.parse_response(output.sequences[0].tokens)
print(f"Sampled message: {sampled_message}")
print(f"Parse success: {parse_success}")
```
We get the following output:
```
Stop sequences: [151645]
Sampled tokens: [45, 7741, 34651, 31410, 614, 4911, 76665, 11, 2670, 264, 7548, 11050, 22077, 1849, 323, 264, 1602, 3347, 40761, 4379, 11, 892, 16792, 311, 862, 57119, 13, 151645]
Sampled message: {'role': 'assistant', 'content': 'Naked mole rats have unique adaptations, including a highly efficient immune system and a very low metabolic rate, which contribute to their longevity.'}
Parse success: True
```
You can see that the there is one stop sequence, 151645, which you can verify is the `<|im_end|>` token. The output is parsed successfully into a message.
## Supervised learning
For supervised learning, along with some other algorithms like [DPO](/preferences/dpo-guide), we need different information from the renderer -- we want to provide a target assistant message, and the renderer needs to tell us which tokens are part of the prompt and completion.
To do this, we can use `build_supervised_example` as follows:
```python
tokens, weights = renderer.build_supervised_example(messages)
from tinker_cookbook.utils.format_colorized import format_colorized
print(format_colorized(tokens, weights, tokenizer))
```
We get the following output:
<div className="example">
<span className="prompt"><|im_start|>system↵<br />Answer concisely; at most one sentence per response<|im_end|>↵<br /><|im_start|>user↵<br />What is the longest-lived rodent species?<|im_end|>↵<br /><|im_start|>assistant↵<br />The naked mole rat, which can live over 30 years.<|im_end|>↵<br /><|im_start|>user↵<br />How do they live so long?<|im_end|>↵<br /><|im_start|>assistant↵<br /></span>
<span className="completion">They evolved multiple protective mechanisms including special hyaluronic acid that prevents cancer, extremely stable proteins, and efficient DNA repair systems that work together to prevent aging.<|im_end|><br /></span>