|
| 1 | +"""Pruebas unitarias base para operaciones de Tensor y autograd.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from ttensor import Device |
| 8 | +from ttensor import DeviceManager |
| 9 | +from ttensor import Tensor |
| 10 | + |
| 11 | + |
| 12 | +def _has_gpu() -> bool: |
| 13 | + try: |
| 14 | + DeviceManager.initialize() |
| 15 | + return DeviceManager.device_count() > 0 |
| 16 | + except Exception: |
| 17 | + return False |
| 18 | + |
| 19 | + |
| 20 | +def test_tensor_add_cpu() -> None: |
| 21 | + a = Tensor.from_list([1.0, 2.0, 3.0, 4.0], rows=2, cols=2, device=Device.CPU, requires_grad=False) |
| 22 | + b = Tensor.from_list([10.0, 20.0, 30.0, 40.0], rows=2, cols=2, device=Device.CPU, requires_grad=False) |
| 23 | + |
| 24 | + c = Tensor.add(a, b) |
| 25 | + |
| 26 | + assert c.tolist() == [11.0, 22.0, 33.0, 44.0] |
| 27 | + |
| 28 | + |
| 29 | +def test_autograd_square_grad_cpu() -> None: |
| 30 | + x = Tensor.from_list([3.0], rows=1, cols=1, device=Device.CPU, requires_grad=True) |
| 31 | + |
| 32 | + y = Tensor.mul(x, x) # f(x) = x^2 |
| 33 | + y.backward() |
| 34 | + |
| 35 | + assert x.grad is not None |
| 36 | + assert x.grad.item() == pytest.approx(6.0, rel=1e-6, abs=1e-6) |
| 37 | + |
| 38 | + |
| 39 | +def test_matmul_cpu_gpu_consistency() -> None: |
| 40 | + if not _has_gpu(): |
| 41 | + pytest.skip("No hay GPU CUDA disponible en este entorno") |
| 42 | + |
| 43 | + values_a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] |
| 44 | + values_b = [7.0, 8.0, 9.0, 10.0, 11.0, 12.0] |
| 45 | + |
| 46 | + a_cpu = Tensor.from_list(values_a, rows=2, cols=3, device=Device.CPU, requires_grad=False) |
| 47 | + b_cpu = Tensor.from_list(values_b, rows=3, cols=2, device=Device.CPU, requires_grad=False) |
| 48 | + out_cpu = Tensor.matmul(a_cpu, b_cpu).tolist() |
| 49 | + |
| 50 | + a_gpu = Tensor.from_list(values_a, rows=2, cols=3, device=Device.GPU, requires_grad=False) |
| 51 | + b_gpu = Tensor.from_list(values_b, rows=3, cols=2, device=Device.GPU, requires_grad=False) |
| 52 | + out_gpu = Tensor.matmul(a_gpu, b_gpu).tolist() |
| 53 | + |
| 54 | + assert len(out_cpu) == len(out_gpu) |
| 55 | + for cpu_v, gpu_v in zip(out_cpu, out_gpu): |
| 56 | + assert gpu_v == pytest.approx(cpu_v, rel=1e-5, abs=1e-5) |
0 commit comments