File size: 2,458 Bytes
779ff0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The training settings handed to Laya: the task's changes, and nothing else moved."""

from __future__ import annotations

import importlib.util
import unittest

from layatasks import train
from layatasks.task import TASKS, load


@unittest.skipUnless(importlib.util.find_spec("laya"), "laya is not installed")
class ConfigTests(unittest.TestCase):
    def test_task_settings_reach_laya_and_the_rest_stay_default(self):
        from laya.train import TrainConfig

        default = TrainConfig()
        for name in TASKS:
            task = load(name).TASK
            cfg = train.config(task, seed=3)
            self.assertEqual((cfg.seed, cfg.epochs, cfg.max_len, cfg.head_max_len, cfg.target_error, cfg.loss),
                             (3, task.epochs, task.max_len, task.head_max_len, task.target_error, task.loss))
            self.assertEqual((cfg.micro_batch, cfg.grad_accum), (default.micro_batch, default.grad_accum))
            for field in ("encoder_lr", "head_lr", "calib_max", "calib_seed", "shuffle_options"):
                self.assertEqual(getattr(cfg, field), getattr(default, field), field)

    def test_smaller_micro_batches_keep_the_step_at_64_rows(self):
        task = load(TASKS[0]).TASK
        cfg = train.config(task, seed=0, micro_batch=4)
        self.assertEqual((cfg.micro_batch, cfg.grad_accum), (4, 16))
        with self.assertRaises(ValueError):
            train.config(task, seed=0, micro_batch=6)


class DevSplitTests(unittest.TestCase):
    def rows(self):
        # Every third text repeats, as contract boilerplate does.
        return [{"state": "provision %d" % (i // 3 if i % 3 == 0 else i), "n": i} for i in range(300)]

    def test_dev_texts_are_new_to_training(self):
        rows = self.rows()
        kept, dev = train.split_dev(rows, 40)
        self.assertEqual(len(dev), 40)
        dev_texts = {r["state"] for r in dev}
        self.assertFalse(dev_texts & {r["state"] for r in kept})
        self.assertEqual(len({r["n"] for r in kept} & {r["n"] for r in dev}), 0)
        dropped = len(rows) - len(kept) - len(dev)
        self.assertEqual(dropped, sum(1 for r in rows if r["state"] in dev_texts) - len(dev))

    def test_same_rows_every_time(self):
        a, b = train.split_dev(self.rows(), 40), train.split_dev(self.rows(), 40)
        self.assertEqual(a, b)
        self.assertNotEqual(train.split_dev(self.rows(), 40, seed=1)[1], a[1])


if __name__ == "__main__":
    unittest.main()