|
20 | 20 | import functools |
21 | 21 | from typing import Union |
22 | 22 |
|
| 23 | +from etils import epy |
23 | 24 | import jax |
| 25 | +import kauldron as kd |
24 | 26 | from kauldron.cli import cmd_utils as cu |
25 | 27 | from kauldron.data import utils as data_utils |
26 | 28 | import tensorflow_datasets as tfds |
@@ -71,17 +73,66 @@ def __call__(self) -> None: |
71 | 73 | # TODO(klausg): could try to run the metrics computation too. |
72 | 74 |
|
73 | 75 |
|
| 76 | +@dataclasses.dataclass(frozen=True, kw_only=True) |
| 77 | +class Train(cu.SubCommand): |
| 78 | + """Run trainer.train().""" |
| 79 | + |
| 80 | + def __call__(self) -> None: |
| 81 | + self.print_config_origin() |
| 82 | + |
| 83 | + # Ensure exactly one training step is performed to match kd_test.ipynb |
| 84 | + self.cfg.stop_after_steps = 1 |
| 85 | + |
| 86 | + if hasattr(self.cfg, 'evals'): |
| 87 | + kd.kontext.set_by_path(self.cfg, 'evals.**.num_batches', 1) |
| 88 | + |
| 89 | + trainer = self.trainer # trigger config resolution |
| 90 | + |
| 91 | + with cu.timed('trainer.train()'): |
| 92 | + train_state, aux = trainer.train() |
| 93 | + del train_state, aux |
| 94 | + # We don't print the output of train() as it might be very verbose |
| 95 | + # but we can print that it succeeded. |
| 96 | + print('Successfully completed trainer.train()') |
| 97 | + |
| 98 | +@dataclasses.dataclass(frozen=True, kw_only=True) |
| 99 | +class Eval(cu.SubCommand): |
| 100 | + """Run trainer.eval().""" |
| 101 | + |
| 102 | + def __call__(self) -> None: |
| 103 | + self.print_config_origin() |
| 104 | + |
| 105 | + if hasattr(self.cfg, 'evals'): |
| 106 | + kd.kontext.set_by_path(self.cfg, 'evals.**.num_batches', 1) |
| 107 | + |
| 108 | + trainer = self.trainer # trigger config resolution |
| 109 | + |
| 110 | + with cu.timed('trainer.init_state()'): |
| 111 | + state = trainer.init_state() |
| 112 | + |
| 113 | + eval_metrics = {} |
| 114 | + for name, evaluator in trainer.evals.items(): |
| 115 | + with cu.timed(f'evaluator.evaluate({name})'): |
| 116 | + eval_metrics[name] = evaluator.evaluate(state=state, step=0) |
| 117 | + |
| 118 | + if eval_metrics: |
| 119 | + print('Evaluator metrics:') |
| 120 | + epy.pprint(eval_metrics) |
| 121 | + |
| 122 | + |
74 | 123 | _SUBCOMMANDS = { |
75 | 124 | # Manually name the subcommand 'eval_shape' beacause simple-parsing |
76 | 125 | # would turn this into 'evalshape' instead. |
77 | 126 | 'eval_shape': EvalShape, |
| 127 | + 'train': Train, |
| 128 | + 'eval': Eval, |
78 | 129 | } |
79 | 130 |
|
80 | 131 |
|
81 | 132 | @dataclasses.dataclass(frozen=True, kw_only=True) |
82 | 133 | class Run(cu.CommandGroup): |
83 | 134 | """Run commands for local training validation.""" |
84 | 135 |
|
85 | | - sub_command: Union[EvalShape] = dataclasses.field( |
| 136 | + sub_command: Union[EvalShape, Train, Eval] = dataclasses.field( |
86 | 137 | metadata={'subparsers': _SUBCOMMANDS} |
87 | 138 | ) |
0 commit comments