"""Hand-set CPU/float64 LSTM/GRU mechanisms; no training/benchmark.

Plain Python uses column-vector equations (matrix rows = output features).
PyTorch parameters stack gate rows: LSTM i,f,g,o; GRU r,z,n.
"""
import json
import math
import platform
import torch


def mv(matrix, vector):
    return [sum(a*b for a, b in zip(row, vector)) for row in matrix]


def sigmoid(v):
    return 1 / (1 + math.exp(-v))


def affine(x, h, p):
    wx, wh = mv(p['W_i'], x), mv(p['W_h'], h)
    return [wx[j] + p['b_i'][j] + wh[j] + p['b_h'][j] for j in range(2)]


def tensor(value):
    return torch.tensor(value, dtype=torch.float64, device='cpu')


def load_cell(cell, gates, order):
    with torch.no_grad():
        for name, key in [('weight_ih', 'W_i'), ('weight_hh', 'W_h'),
                          ('bias_ih', 'b_i'), ('bias_hh', 'b_h')]:
            # Each matrix contributes2 rows; each bias contributes2 entries.
            packed = [row for g in order for row in gates[g][key]]
            getattr(cell, name).copy_(tensor(packed))


def main():
    torch.manual_seed(43)  # All randomized initialization is overwritten.
    x, h, c = [0.6, -0.4], [0.3, -0.2], [2.4, -1.8]
    lstm_params = {
        'i': {'W_i': [[.4, -.2], [.1, .3]], 'W_h': [[.5, .15], [-.25, .4]],
              'b_i': [.05, -.1], 'b_h': [-.02, .03]},
        'f': {'W_i': [[-.3, .2], [.25, -.1]], 'W_h': [[.2, -.35], [.15, .3]],
              'b_i': [.2, .1], 'b_h': [.04, -.06]},
        'g': {'W_i': [[.2, .5], [-.4, .3]], 'W_h': [[.3, -.2], [.4, .1]],
              'b_i': [-.1, .05], 'b_h': [.07, -.03]},
        'o': {'W_i': [[.1, -.3], [.2, .4]], 'W_h': [[-.2, .25], [.3, -.15]],
              'b_i': [.1, -.05], 'b_h': [-.04, .02]}}
    pre = {name: affine(x, h, p) for name, p in lstm_params.items()}
    gates = {name: [(math.tanh(v) if name == 'g' else sigmoid(v)) for v in values]
             for name, values in pre.items()}
    retained = [gates['f'][j] * c[j] for j in range(2)]
    written = [gates['i'][j] * gates['g'][j] for j in range(2)]
    c_new = [retained[j] + written[j] for j in range(2)]
    h_new = [gates['o'][j] * math.tanh(c_new[j]) for j in range(2)]
    cell = torch.nn.LSTMCell(2, 2, bias=True, device='cpu', dtype=torch.float64)
    load_cell(cell, lstm_params, ['i', 'f', 'g', 'o'])
    with torch.no_grad():
        torch_h, torch_c = cell(tensor([x]), (tensor([h]), tensor([c])))
    torch.testing.assert_close(torch_h, tensor([h_new]), rtol=0, atol=1e-14)
    torch.testing.assert_close(torch_c, tensor([c_new]), rtol=0, atol=1e-14)
    assert any(abs(v) > 1 for v in c_new)  # C is not restricted to (-1,1).
    assert all(abs(v) < 1 for v in h_new)
    assert all(0 < v < 1 for name in ['i', 'f', 'o'] for v in gates[name])
    assert all(abs(v) < 1 for v in gates['g'])

    # Isolated direct C carry: fixed artificial f, no writes, gates independent of C.
    # This is deliberately NOT the total derivative of a full recurrent LSTM.
    decay = []
    for f in [.9, .2]:
        values = [1.0]
        for _ in range(10):
            values.append(f * values[-1])
        c0 = tensor(1.0).requires_grad_()
        propagated = c0
        for _ in range(10):
            propagated = f * propagated
        derivative = torch.autograd.grad(propagated, c0)[0].item()
        assert math.isclose(derivative, f**10, rel_tol=1e-14, abs_tol=1e-16)
        decay.append({'fixed_f': f, 'c_t_from_t0_to_t10': values,
                      'direct_path_dc10_dc0': derivative, 'closed_form_f_power_10': f**10})

    gru_params = {
        'r': {'W_i': [[.4, -.3], [-.2, .5]], 'W_h': [[.2, .35], [-.4, .1]],
              'b_i': [.1, -.15], 'b_h': [.05, -.02]},
        'z': {'W_i': [[-.1, .2], [.3, .15]], 'W_h': [[.4, -.2], [.1, .3]],
              'b_i': [-.05, .08], 'b_h': [.03, -.04]},
        'n': {'W_i': [[.25, -.4], [.3, .2]], 'W_h': [[.6, -.5], [.4, .3]],
              'b_i': [.07, -.09], 'b_h': [.2, -.15]}}
    r = [sigmoid(v) for v in affine(x, h, gru_params['r'])]
    z = [sigmoid(v) for v in affine(x, h, gru_params['z'])]
    n_params = gru_params['n']
    input_term = [a+b for a, b in zip(mv(n_params['W_i'], x), n_params['b_i'])]
    h_linear = mv(n_params['W_h'], h)
    reset_h_linear = mv(n_params['W_h'], [r[j]*h[j] for j in range(2)])
    # D2L reset-before: combine biases into b_n=b_in+b_hn, outside reset.
    before_a = [input_term[j] + reset_h_linear[j] + n_params['b_h'][j] for j in range(2)]
    # PyTorch reset-after: r multiplies BOTH recurrent projection and its bias.
    after_a = [input_term[j] + r[j]*(h_linear[j]+n_params['b_h'][j]) for j in range(2)]
    n_before, n_after = [math.tanh(v) for v in before_a], [math.tanh(v) for v in after_a]
    h_before = [(1-z[j])*n_before[j] + z[j]*h[j] for j in range(2)]
    h_after = [(1-z[j])*n_after[j] + z[j]*h[j] for j in range(2)]
    gru = torch.nn.GRUCell(2, 2, bias=True, device='cpu', dtype=torch.float64)
    load_cell(gru, gru_params, ['r', 'z', 'n'])
    with torch.no_grad():
        builtin_gru = gru(tensor([x]), tensor([h]))
    torch.testing.assert_close(builtin_gru, tensor([h_after]), rtol=0, atol=1e-14)
    assert abs(r[0]-r[1]) > .05
    assert all(n_params['W_h'][i][1-i] != 0 for i in range(2))
    assert all(v != 0 for v in n_params['b_h'])
    assert max(abs(a-b) for a, b in zip(n_before, n_after)) > .01
    assert max(abs(a-b) for a, b in zip(h_before, h_after)) > .01
    # Separate noncommuting matrix/reset term from recurrent-bias placement term.
    matrix_difference = [r[j]*h_linear[j]-reset_h_linear[j] for j in range(2)]
    bias_difference = [(r[j]-1)*n_params['b_h'][j] for j in range(2)]
    for j in range(2):
        assert math.isclose(after_a[j]-before_a[j], matrix_difference[j]+bias_difference[j], abs_tol=1e-14)
    mix = []
    for forced_z in [.99, .01]:
        mixed = [(1-forced_z)*n_after[j]+forced_z*h[j] for j in range(2)]
        mix.append({'artificial_fixed_z': forced_z, 'mixed_hidden': mixed,
                    'max_distance_to_old_hidden': max(abs(mixed[j]-h[j]) for j in range(2)),
                    'max_distance_to_candidate': max(abs(mixed[j]-n_after[j]) for j in range(2))})
    assert mix[0]['max_distance_to_old_hidden'] < mix[1]['max_distance_to_old_hidden']

    result = {
        'scope': 'Hand-set mechanics only, CPU float64, no text corpus/training/benchmark or guaranteed memory quality.',
        'environment': {'python': platform.python_version(), 'torch': torch.__version__, 'device': str(torch_h.device), 'dtype': str(torch_h.dtype)},
        'inputs': {'x': x, 'previous_hidden': h, 'previous_cell_lstm': c, 'batched_shapes': {'x':[1,2], 'h':[1,2], 'c':[1,2]}},
        'lstm': {'gate_stack_order': ['i','f','g','o'], 'parameters_column_orientation': lstm_params,
                 'preactivations': pre, 'gate_values': gates, 'retained_f_times_c': retained,
                 'written_i_times_g': written, 'manual_c_new': c_new, 'manual_h_new': h_new,
                 'builtin_c_new': torch_c.squeeze(0).tolist(), 'builtin_h_new': torch_h.squeeze(0).tolist(),
                 'max_abs_cell_error': (torch_c-tensor([c_new])).abs().max().item(),
                 'max_abs_hidden_error': (torch_h-tensor([h_new])).abs().max().item(),
                 'range_note': 'i/f/o in(0,1),g/h in(-1,1); C itself is not bounded to(-1,1).'},
        'fixed_gate_direct_cell_path': {'scope': 'Artificial C_t=f*C_prev with writes zero and fixed gate independent of states. Direct-path derivative only; NOT total full-LSTM gradient or task quality.', 'series': decay},
        'gru': {'gate_stack_order': ['r','z','n'], 'parameters_column_orientation': gru_params, 'reset_r': r, 'update_z': z,
                'input_candidate_affine': input_term, 'recurrent_h_projection_without_bias': h_linear,
                'reset_before_recurrent_projection': reset_h_linear,
                'd2l_equivalent_single_candidate_bias': [n_params['b_i'][j]+n_params['b_h'][j] for j in range(2)],
                'reset_before_candidate_preactivation': before_a, 'reset_after_candidate_preactivation': after_a,
                'reset_before_candidate': n_before, 'reset_after_candidate': n_after,
                'reset_before_hidden': h_before, 'manual_pytorch_hidden': h_after, 'builtin_pytorch_hidden': builtin_gru.squeeze(0).tolist(),
                'max_abs_builtin_manual_error': (builtin_gru-tensor([h_after])).abs().max().item(),
                'max_abs_variant_hidden_difference': max(abs(a-b) for a,b in zip(h_before,h_after)),
                'preactivation_difference_matrix_noncommutation': matrix_difference,
                'preactivation_difference_bias_placement': bias_difference,
                'variant_note': 'Reset-before uses W_hn(r*h)+b_hn; PyTorch uses r*(W_hn*h+b_hn). Same r/z/weights/input; differences are matrix order AND bias placement, not precision error.'},
        'fixed_z_interpolation': {'scope':'Artificial z substitution with same fixed old hidden/candidate; not a trained gate or probability of remembering.', 'cases':mix},
        'checks': 'PASS: Python LSTM vs nn.LSTMCell; ranges; isolated fixed-f path autograd; GRU variants differ; Python reset-after vs nn.GRUCell; difference decomposition; z-near1 preserves old hidden.'}
    print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))


if __name__ == '__main__':
    main()
