File size: 13,422 Bytes
ca3db1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Arithmetic data for YugoGPT Croatian v1: every answer computed and checked by Python.

Targets the 2024 CroGuana weakness (33 + 7 -> 39): the Mistral tokenizer already splits digits, so rows teach the
procedure. Column addition with carries, subtraction with borrows, multiplication by partial products, long division
with remainder, order of operations, percentages, decimal-comma money, time; word problems (Croatian with case agreement
from the MiniMind noun table, and English). Answer styles: <think> steps + answer, answer only, answer + inverse check.

python arith.py   ->  arith-train.jsonl (SFT), arith-probe.jsonl (held-out probes, separate seed, never in training)
"""
import json
import random
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
from short_arith import NAMES, NOUNS, FITS, OBJ, EN_NAMES, agree, eur, verb

DIG = {'hr': ('pišem', 'prenosim', 'posuđujem'), 'en': ('write', 'carry', 'borrow')}


def operands(rng, kind):
    """Operand pairs biased towards carries/borrows and edge cases."""
    r = rng.random()
    if r < 0.12:  # edge cases
        e = rng.choice([(10 ** rng.randint(1, 4) - 1, rng.randint(1, 9)), (10 ** rng.randint(2, 4), rng.randint(1, 9)),
                        (rng.randint(1, 9) * 10 + rng.randint(1, 9), 10 - rng.randint(1, 9))])
        return e
    da, db = rng.choice([(1, 1), (2, 1), (2, 1), (2, 2), (2, 2), (3, 2), (3, 3), (4, 3), (4, 4), (5, 4)])
    a, b = rng.randint(10 ** (da - 1), 10 ** da - 1), rng.randint(10 ** (db - 1), 10 ** db - 1)
    if r < 0.45 and kind in '+-':  # force a units carry/borrow
        if kind == '+':
            b = b - b % 10 + max(b % 10, 10 - a % 10) if (a % 10 + b % 10) < 10 and a % 10 else b
        elif a % 10 >= b % 10 and b % 10 < 9:
            b = b - b % 10 + rng.randint(a % 10 + 1, 9) if a % 10 < 9 else b
    return a, b


def col_add(a, b, L):
    w, c = DIG[L][0], DIG[L][1]
    xs, ys, carry, out, steps = str(a)[::-1], str(b)[::-1], 0, [], []
    for i in range(max(len(xs), len(ys))):
        x, y = int(xs[i]) if i < len(xs) else 0, int(ys[i]) if i < len(ys) else 0
        s = x + y + carry
        expr = f'{x} + {y}' + (f' + {carry}' if carry else '')
        out.append(s % 10)
        steps.append(f'{expr} = {s}, {w} {s % 10}' + (f', {c} {s // 10}' if s >= 10 else ''))
        carry = s // 10
    if carry:
        steps.append(f'{w} {carry}' if L == 'en' else f'{w} {carry} ispred')
    return steps


def col_sub(a, b, L):
    w, br = DIG[L][0], DIG[L][2]
    xs, ys, borrow, steps = str(a)[::-1], str(b)[::-1], 0, []
    lent = 'posuđeno' if L == 'hr' else 'borrowed'
    for i in range(len(xs)):
        x0, y = int(xs[i]), int(ys[i]) if i < len(ys) else 0
        x = x0 - borrow
        pre = f'{x0} - 1 ({lent}) = {x}; ' if borrow else ''
        if x < y:
            steps.append(f'{pre}{x} < {y}, {br} 1: {x + 10} - {y} = {x + 10 - y}, {w} {x + 10 - y}')
            borrow = 1
        else:
            steps.append(f'{pre}{x} - {y} = {x - y}, {w} {x - y}')
            borrow = 0
    return steps


def col_mul(a, b, L):
    w, c = DIG[L][0], DIG[L][1]
    if b < 10:
        steps, carry = [], 0
        for d in str(a)[::-1]:
            p = int(d) * b + carry
            steps.append(f'{d} × {b}' + (f' + {carry}' if carry else '') + f' = {p}, {w} {p % 10}' + (f', {c} {p // 10}' if p >= 10 else ''))
            carry = p // 10
        if carry:
            steps.append(f'{w} {carry}' if L == 'en' else f'{w} {carry} ispred')
        return steps
    parts = [(int(d) * 10 ** i) for i, d in enumerate(str(b)[::-1]) if d != '0']
    lines = [f'{b} = ' + ' + '.join(map(str, parts[::-1]))] + [f'{a} × {p} = {a * p}' for p in parts[::-1]]
    lines.append(' + '.join(str(a * p) for p in parts[::-1]) + f' = {a * b}')
    return lines


def long_div(a, b, L):
    steps, rest = [], 0
    for d in str(a):
        cur = rest * 10 + int(d)
        q, rest = divmod(cur, b)
        if cur >= b or steps:
            steps.append(f'{cur} : {b} = {q}' + (f', ostatak {rest}' if L == 'hr' else f', remainder {rest}'))
    return steps or [f'{a} : {b} = 0, ' + ('ostatak' if L == 'hr' else 'remainder') + f' {a}']


Q = {
    'hr': {'+': ['Koliko je {a} + {b}?', '{a} + {b} =', 'Izračunaj {a} + {b}.', 'Zbroji {a} i {b}.', 'Koliko je {a} plus {b}?'],
           '-': ['Koliko je {a} - {b}?', '{a} - {b} =', 'Izračunaj {a} - {b}.', 'Oduzmi {b} od {a}.', 'Koliko je {a} minus {b}?'],
           '*': ['Koliko je {a} × {b}?', '{a} * {b} =', 'Izračunaj {a} puta {b}.', 'Pomnoži {a} i {b}.'],
           '/': ['Koliko je {a} : {b}?', 'Podijeli {a} s {b}.', 'Izračunaj {a} / {b} (s ostatkom ako ga ima).']},
    'en': {'+': ['What is {a} + {b}?', '{a} + {b} =', 'Add {a} and {b}.', 'Calculate {a} plus {b}.'],
           '-': ['What is {a} - {b}?', '{a} - {b} =', 'Subtract {b} from {a}.'],
           '*': ['What is {a} × {b}?', '{a} * {b} =', 'Multiply {a} by {b}.'],
           '/': ['What is {a} ÷ {b}?', 'Divide {a} by {b}.']},
}


def bare(rng, L):
    op = rng.choice('++--*/')
    a, b = operands(rng, op)
    if op == '-' and a < b:
        a, b = b, a
    if op == '*':
        a, b = rng.randint(2, 999), rng.choice([rng.randint(2, 9), rng.randint(2, 9), rng.randint(11, 99)])
    if op == '/':
        b = rng.randint(2, 12) if rng.random() < 0.7 else rng.randint(13, 40)
        a = b * rng.randint(2, 300) + (rng.randint(1, b - 1) if rng.random() < 0.35 else 0)
    q = rng.choice(Q[L][op]).format(a=a, b=b)
    if op == '+':
        ans, steps, check = a + b, col_add(a, b, L), f'{a + b} - {b} = {a}'
    elif op == '-':
        ans, steps, check = a - b, col_sub(a, b, L), f'{a - b} + {b} = {a}'
    elif op == '*':
        ans, steps, check = a * b, col_mul(a, b, L), f'{a * b} : {b} = {a}'
    else:
        qq, r = divmod(a, b)
        ans = (f'{qq}, ostatak {r}' if L == 'hr' else f'{qq}, remainder {r}') if r else qq
        steps, check = long_div(a, b, L), f'{qq} × {b}' + (f' + {r}' if r else '') + f' = {a}'
    sym = {'+': '+', '-': '-', '*': '×', '/': ':'}[op]
    head = f'{a} {sym} {b}'
    return q, head, steps, ans, check, (op, a, b)


def expr(rng, L):
    """Order of operations with brackets: a + b × c, (a + b) × c, a × b - c."""
    a, b, c = rng.randint(2, 50), rng.randint(2, 20), rng.randint(2, 12)
    t = rng.randrange(3)
    if t == 0:
        s, steps = f'{a} + {b} × {c}', [f'{b} × {c} = {b * c}', f'{a} + {b * c} = {a + b * c}']
        ans = a + b * c
    elif t == 1:
        s, steps = f'({a} + {b}) × {c}', [f'{a} + {b} = {a + b}', f'{a + b} × {c} = {(a + b) * c}']
        ans = (a + b) * c
    else:
        a = max(a, 2)
        s, steps = f'{a} × {c} - {b}', [f'{a} × {c} = {a * c}', f'{a * c} - {b} = {a * c - b}']
        ans = a * c - b
    rule = 'Prvo množenje (i zagrade), zatim zbrajanje i oduzimanje.' if L == 'hr' else 'Brackets and multiplication first, then addition and subtraction.'
    q = (f'Koliko je {s}?' if L == 'hr' else f'What is {s}?')
    return q, s, [rule] + steps, ans, None, ('e', s, 0)


def money(rng, L):
    p = rng.randint(105, 2999) / 100  # price with cents
    n = rng.randint(2, 9)
    tot = round(p * n, 2)
    f = (lambda x: f'{x:.2f}'.replace('.', ',')) if L == 'hr' else (lambda x: f'{x:.2f}')
    q = (f'Jedna bilježnica stoji {f(p)} €. Koliko stoji {n} bilježnica?' if L == 'hr' and n >= 5 else
         f'Jedna bilježnica stoji {f(p)} €. Koliko stoje {n} bilježnice?' if L == 'hr' else
         f'One notebook costs €{f(p)}. How much do {n} notebooks cost?')
    cents = round(p * 100)
    steps = [('Računam u centima: ' if L == 'hr' else 'Work in cents: ') + f'{f(p)} € = {cents} c',
             *col_mul(cents, n, L), f'{cents * n} c = {f(tot)} €']
    return q, f'{n} × {f(p)}', steps, f'{f(tot)} €', None, ('m', cents, n)


def percent(rng, L):
    base = rng.choice([20, 40, 50, 60, 80, 120, 150, 200, 250, 300, 400, 480, 600, 750, 1200])
    pc = rng.choice([5, 10, 15, 20, 25, 30, 40, 50, 75])
    val = base * pc / 100
    v = int(val) if val == int(val) else str(val).replace('.', ',' if L == 'hr' else '.')
    q = f'Koliko je {pc} % od {base}?' if L == 'hr' else f'What is {pc}% of {base}?'
    steps = [f'{pc} % = {pc}/100', f'{base} × {pc} = {base * pc}', f'{base * pc} : 100 = {v}']
    return q, f'{pc} % od {base}' if L == 'hr' else f'{pc}% of {base}', steps, v, None, ('p', base, pc)


def word_hr(rng):
    name, g = rng.choice(NAMES)
    ow = rng.choice(OBJ)
    o, c = NOUNS[ow], NOUNS[rng.choice(FITS[ow])]
    t = rng.randrange(4)
    if t == 0:
        a, b = operands(rng, '+')
        a, b = min(a, 999), min(b, 999)
        q = f'{name} ima {a} {agree(a, o, "A")}. {verb(g, "Dobio", "Dobila")} je još {b} {agree(b, o, "A")}. Koliko {o["Gmn"]} {name} sada ima?'
        return q, f'{a} + {b}', col_add(a, b, 'hr'), a + b, f'{a + b} - {b} = {a}', ('+', a, b), f'{name} sada ima {a + b} {agree(a + b, o, "A")}.'
    if t == 1:
        a, b = operands(rng, '-')
        a, b = max(a, b), min(a, b)
        q = f'U {c["L"]} ima {a} {agree(a, o, "A")}. {name} je {verb(g, "uzeo", "uzela")} {b} {agree(b, o, "A")}. Koliko {o["Gmn"]} je ostalo u {c["L"]}?'
        return q, f'{a} - {b}', col_sub(a, b, 'hr'), a - b, f'{a - b} + {b} = {a}', ('-', a, b), f'U {c["L"]} je ostalo {a - b} {agree(a - b, o, "A")}.'
    if t == 2:
        a, b = rng.randint(2, 99), rng.randint(2, 12)
        q = f'U svakoj {c["L"]} ima {a} {agree(a, o, "A")}. Koliko {o["Gmn"]} ima u {b} {agree(b, c)}?'
        return q, f'{b} × {a}', col_mul(a, b, 'hr'), a * b, f'{a * b} : {b} = {a}', ('*', a, b), f'U {b} {agree(b, c)} ima {a * b} {agree(a * b, o, "A")}.'
    b = rng.randint(2, 9)
    k = rng.randint(2, 40)
    a = b * k
    q = f'{name} ima {a} {agree(a, o, "A")} i {verb(g, "želi", "želi")} ih jednako rasporediti u {b} {agree(b, c, "A")}. Koliko će {o["Gmn"]} biti u svakoj {c["L"]}?'
    return q, f'{a} : {b}', long_div(a, b, 'hr'), k, f'{k} × {b} = {a}', ('/', a, b), f'U svakoj {c["L"]} bit će {k} {agree(k, o)}.'


def word_en(rng):
    n = rng.choice(EN_NAMES)
    o = rng.choice(['apples', 'books', 'pencils', 'cards', 'stones', 'stickers', 'marbles'])
    t = rng.randrange(3)
    if t == 0:
        a, b = operands(rng, '+')
        return (f'{n} has {a} {o} and gets {b} more. How many {o} does {n} have now?', f'{a} + {b}', col_add(a, b, 'en'), a + b,
                f'{a + b} - {b} = {a}', ('+', a, b), f'{n} now has {a + b} {o}.')
    if t == 1:
        a, b = operands(rng, '-')
        a, b = max(a, b), min(a, b)
        return (f'There are {a} {o} in a box. {n} takes out {b}. How many are left?', f'{a} - {b}', col_sub(a, b, 'en'), a - b,
                f'{a - b} + {b} = {a}', ('-', a, b), f'{a - b} {o} are left.')
    a, b = rng.randint(2, 99), rng.randint(2, 12)
    return (f'Each bag holds {a} {o}. How many {o} are in {b} bags?', f'{b} × {a}', col_mul(a, b, 'en'), a * b,
            f'{a * b} : {b} = {a}', ('*', a, b), f'There are {a * b} {o} in {b} bags.')


def render(rng, L, item, style):
    q, head, steps, ans, check, key, *prose = item
    final = prose[0] if prose else (f'{head} = {ans}' if key[0] in '+-*/' else str(ans))
    if style == 'short':
        return q, (prose[0] if prose else str(ans)), key
    think = '\n'.join(steps)
    if check and style == 'check':
        think += '\n' + ('Provjera: ' if L == 'hr' else 'Check: ') + check
    if L == 'hr' and key[0] in '+-*/':
        think = ('Računam po stupcima, od jedinica prema većim mjestima.\n' if key[0] in '+-' and key[1] >= 10 else '') + think
    return q, f'<think>\n{think}\n</think>\n{final}', key


def make(seed, n, exclude=frozenset()):
    rng = random.Random(seed)
    rows, keys = [], set()
    gens = [(bare, 0.42), (word_hr, 0.2), (word_en, 0.08), (expr, 0.12), (money, 0.08), (percent, 0.10)]
    while len(rows) < n:
        g = rng.choices([x for x, _ in gens], [w for _, w in gens])[0]
        L = 'en' if g is word_en else ('hr' if g is word_hr else ('en' if rng.random() < 0.3 else 'hr'))
        item = g(rng) if g in (word_hr, word_en) else g(rng, L)
        q, a, key = render(rng, L, item, rng.choices(['think', 'check', 'short'], [0.5, 0.3, 0.2])[0])
        if key in exclude:
            continue
        keys.add(key)
        rows.append(dict(id=f'yg-arith:{seed}:{len(rows)}', lang=L, messages=[dict(role='user', content=q), dict(role='assistant', content=a)]))
    return rows, keys


def selfcheck(rows):
    """Re-verify every stated final number for bare + - × rows by evaluating the head expression."""
    bad = 0
    for r in rows:
        a = r['messages'][1]['content'].split('\n')[-1]
        if ' = ' in a and a.count('=') == 1:
            lhs, rhs = a.split(' = ')
            lhs = lhs.replace('×', '*')
            if all(ch in '0123456789+-* ' for ch in lhs) and rhs.strip().isdigit():
                bad += eval(lhs) != int(rhs)
    return bad


def main():
    probe, pkeys = make(990001, 600)
    train, _ = make(251125, 40000, exclude=frozenset(pkeys))
    assert selfcheck(train) == 0 and selfcheck(probe) == 0
    for name, rows in (('arith-train.jsonl', train), ('arith-probe.jsonl', probe)):
        with open(HERE / name, 'w') as f:
            for r in rows:
                f.write(json.dumps(r, ensure_ascii=False) + '\n')
    print('train', len(train), 'probe', len(probe), 'probe keys excluded from train')


if __name__ == '__main__':
    main()