File size: 17,444 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# SPDX-License-Identifier: Apache-2.0
"""C03: tensor layout and dtype helpers shared by every port.

Host side (numpy only, no ttnn): tile padding, fixed-capacity padding with a valid count, bf16 bit conversion.
Device side (ttnn imported inside each function): exact host-tensor construction for every dtype (integer arrays are
never routed through a float intermediate), uploads, layout and dtype changes that are no-ops when nothing changes,
fp32 islands (typecast in and out), uint8 uploads with an on-device typecast, readback to numpy, and
:class:`HostStaging`: a persistent host tensor whose buffer is written in place (no ``from_torch`` per frame).

Measured on this p150b (``logs/ttaw/api_probe_20261007.log``): numpy uint32 arrays round-trip exactly (including
values >= 2**31); uint8 -> bf16 ``ttnn.typecast`` is exact in ROW_MAJOR and TILE layout; ``torch.from_dlpack`` of a
host buffer is a writable alias (``numpy.from_dlpack`` is read-only, ``numpy.asarray`` fails).
"""
from __future__ import annotations

import math
from typing import Any, Callable, Optional, Sequence, Tuple, Union

import numpy as np

__all__ = [
    "TILE",
    "round_up",
    "tile_padded_shape",
    "pad_to_tile",
    "pad_to_capacity",
    "as_4d",
    "float32_to_bf16_bits",
    "bf16_bits_to_float32",
    "round_to_bf16",
    "ttnn_dtype",
    "dtype_name",
    "to_host_tensor",
    "to_device",
    "to_numpy",
    "host_view",
    "to_layout",
    "typecast",
    "to_fp32",
    "to_bf16",
    "fp32_island",
    "upload_u8",
    "HostStaging",
]

TILE = 32

ArrayLike = Union[np.ndarray, Sequence, Any]


# ------------------------------------------------------------------------------------------------- host side

def round_up(n: int, multiple: int = TILE) -> int:
    """Smallest multiple of ``multiple`` that is >= ``n``."""
    if multiple <= 0:
        raise ValueError("multiple must be positive")
    return -(-int(n) // multiple) * multiple


def tile_padded_shape(shape: Sequence[int]) -> Tuple[int, ...]:
    """``shape`` with its last two dims rounded up to the 32x32 tile (what a TILE tensor occupies)."""
    shape = tuple(int(s) for s in shape)
    if len(shape) < 2:
        raise ValueError(f"need at least 2 dims, got {shape}")
    return shape[:-2] + (round_up(shape[-2]), round_up(shape[-1]))


def pad_to_tile(array: np.ndarray, value: float = 0.0) -> np.ndarray:
    """Pad the last two dims of a host array up to multiples of 32 with ``value`` (copy only when needed)."""
    a = np.asarray(array)
    target = tile_padded_shape(a.shape)
    if target == a.shape:
        return a
    pad = [(0, 0)] * (a.ndim - 2) + [(0, target[-2] - a.shape[-2]), (0, target[-1] - a.shape[-1])]
    return np.pad(a, pad, mode="constant", constant_values=value)


def pad_to_capacity(array: np.ndarray, capacity: int, *, axis: int = 0, value: float = 0.0,
                    truncate: bool = False) -> Tuple[np.ndarray, int]:
    """Fixed-capacity buffer for a traced graph: pad ``axis`` to ``capacity`` rows with ``value``.

    Returns ``(padded, n_valid)``. More than ``capacity`` rows raise ``ValueError`` unless ``truncate`` keeps the
    first ``capacity`` (the caller must report the overflow). Capacities are grid-independent constants
    (PLAN.md section 0.2)."""
    a = np.asarray(array)
    n = a.shape[axis]
    if n > capacity:
        if not truncate:
            raise ValueError(f"{n} rows exceed the capacity {capacity}")
        return np.take(a, np.arange(capacity), axis=axis), capacity
    if n == capacity:
        return a, n
    pad = [(0, 0)] * a.ndim
    pad[axis] = (0, capacity - n)
    return np.pad(a, pad, mode="constant", constant_values=value), n


def as_4d(array: np.ndarray) -> np.ndarray:
    """Prepend unit dims up to rank 4 (the ``[N, C, H, W]`` / ``[1, 1, rows, cols]`` convention of ttnn)."""
    a = np.asarray(array)
    if a.ndim > 4:
        raise ValueError(f"rank {a.ndim} > 4")
    return a.reshape((1,) * (4 - a.ndim) + a.shape)


def float32_to_bf16_bits(array: ArrayLike) -> np.ndarray:
    """float32 -> bfloat16 bit patterns (uint16), round-to-nearest-even like ``torch.Tensor.to(torch.bfloat16)``.
    NaN stays NaN (quiet bit forced)."""
    f = np.ascontiguousarray(array, dtype=np.float32)
    bits = f.view(np.uint32).astype(np.uint64)
    rounded = (bits + 0x7FFF + ((bits >> 16) & 1)) >> 16
    out = rounded.astype(np.uint16)
    nan = np.isnan(f)
    if nan.any():
        out[nan] = ((bits[nan] >> 16) | 0x0040).astype(np.uint16)
    return out


def bf16_bits_to_float32(bits: ArrayLike) -> np.ndarray:
    """bfloat16 bit patterns (uint16) -> float32 (exact)."""
    b = np.ascontiguousarray(bits, dtype=np.uint16)
    return (b.astype(np.uint32) << 16).view(np.float32)


def round_to_bf16(array: ArrayLike) -> np.ndarray:
    """float32 values rounded to the nearest bfloat16 (RNE), returned as float32: the host emulation of a bf16
    upload, for building exact expectations in tests."""
    return bf16_bits_to_float32(float32_to_bf16_bits(array))


# ----------------------------------------------------------------------------------------------- dtype maps

_DTYPE_ALIASES = {
    "bf16": "bfloat16", "bfloat16": "bfloat16", "fp32": "float32", "float32": "float32", "f32": "float32",
    "bfp8": "bfloat8_b", "bfloat8_b": "bfloat8_b", "bf8": "bfloat8_b", "bfp4": "bfloat4_b", "bfloat4_b": "bfloat4_b",
    "uint32": "uint32", "u32": "uint32", "int32": "int32", "i32": "int32", "uint16": "uint16", "u16": "uint16",
    "uint8": "uint8", "u8": "uint8",
}

# canonical numpy dtype used to build the host tensor for each ttnn dtype (bf16 / bfp go through float32)
_HOST_NUMPY = {"float32": np.float32, "bfloat16": np.float32, "bfloat8_b": np.float32, "bfloat4_b": np.float32,
               "uint32": np.uint32, "int32": np.int32, "uint16": np.uint16, "uint8": np.uint8}


def ttnn_dtype(name_or_dtype: Any):
    """``"bf16"`` / ``"fp32"`` / ``"bfp8"`` / ``"uint32"`` ... (or a ttnn dtype) -> ``ttnn.DataType``."""
    import ttnn

    if not isinstance(name_or_dtype, str):
        return name_or_dtype
    key = _DTYPE_ALIASES.get(name_or_dtype.strip().lower())
    if key is None:
        raise ValueError(f"unknown dtype {name_or_dtype!r}; expected one of {sorted(_DTYPE_ALIASES)}")
    return getattr(ttnn, key)


def dtype_name(dtype: Any) -> str:
    """Canonical lower-case name of a ttnn dtype (``ttnn.bfloat16`` -> ``"bfloat16"``), or of an alias string."""
    if isinstance(dtype, str):
        key = _DTYPE_ALIASES.get(dtype.strip().lower())
        if key is None:
            raise ValueError(f"unknown dtype {dtype!r}")
        return key
    name = getattr(dtype, "name", None) or str(dtype).rsplit(".", 1)[-1]
    name = name.lower()
    return {"bfloat8_b": "bfloat8_b", "bfloat4_b": "bfloat4_b"}.get(name, name)


def _exact_torch(value: ArrayLike, dtype: Any):
    """A torch tensor whose dtype matches ``dtype`` exactly for integers (ttnn would otherwise route int64 through
    bf16) and is float32 / bf16 for float targets."""
    import torch

    name = dtype_name(dtype)
    if isinstance(value, torch.Tensor):
        value = value.detach().cpu()
        if name == "bfloat16":
            return value.to(torch.bfloat16) if value.dtype != torch.bfloat16 else value.contiguous()
        if name in ("float32", "bfloat8_b", "bfloat4_b"):
            return value.to(torch.float32).contiguous()
        value = value.numpy() if value.dtype not in (torch.bfloat16,) else value.float().numpy()
    a = np.asarray(value)
    target = _HOST_NUMPY[name]
    if np.issubdtype(np.dtype(target), np.integer):
        if not (np.issubdtype(a.dtype, np.integer) or a.dtype == np.bool_):
            raise TypeError(f"{name} tensor needs integer data, got {a.dtype}")
        if a.size and np.issubdtype(a.dtype, np.signedinteger) and np.dtype(target).kind == "u" and a.min() < 0:
            raise ValueError(f"negative values cannot be stored as {name}")
    a = np.ascontiguousarray(a, dtype=target)
    if not a.flags.writeable:  # broadcast views are read-only; torch.from_numpy wants writable memory
        a = a.copy()
    t = torch.from_numpy(a)
    return t.to(torch.bfloat16) if name == "bfloat16" else t


# ------------------------------------------------------------------------------------------- device side

def to_host_tensor(value: ArrayLike, dtype: Any, layout: Any = None, *, shape: Optional[Sequence[int]] = None):
    """numpy / torch / ttnn host tensor -> ttnn host tensor of ``dtype`` and ``layout`` (default ROW_MAJOR).

    A ttnn host tensor is checked (dtype, layout, optional shape) and returned unchanged. TILE layout tilizes on the
    host: prefer ROW_MAJOR inputs plus an on-device ``ttnn.to_layout`` for large per-frame tensors."""
    import ttnn

    dtype = ttnn_dtype(dtype)
    layout = ttnn.ROW_MAJOR_LAYOUT if layout is None else layout
    if isinstance(value, ttnn.Tensor):
        if value.storage_type() == ttnn.StorageType.DEVICE:
            raise ValueError("expected a host tensor, got a device tensor")
        if value.dtype != dtype or value.layout != layout:
            raise ValueError(f"host tensor is {value.dtype}/{value.layout}, expected {dtype}/{layout}")
        if shape is not None and tuple(value.shape) != tuple(shape):
            raise ValueError(f"host tensor has shape {tuple(value.shape)}, expected {tuple(shape)}")
        return value
    t = _exact_torch(value, dtype)
    if shape is not None and tuple(t.shape) != tuple(int(s) for s in shape):
        raise ValueError(f"value has shape {tuple(t.shape)}, expected {tuple(shape)}")
    return ttnn.from_torch(t, dtype=dtype, layout=layout)


def to_device(value: ArrayLike, device, dtype: Any = "bf16", layout: Any = None, memory_config: Any = None):
    """Host data -> device tensor (``layout`` default TILE, ``memory_config`` default DRAM interleaved)."""
    import ttnn

    layout = ttnn.TILE_LAYOUT if layout is None else layout
    host = to_host_tensor(value, dtype, layout)
    return ttnn.to_device(host, device, memory_config=memory_config or ttnn.DRAM_MEMORY_CONFIG)


def to_numpy(tensor: Any) -> np.ndarray:
    """ttnn tensor (device or host) / torch tensor / array -> numpy. bf16 becomes float32 (exact); unsigned torch
    dtypes without numpy support are converted through int64."""
    if isinstance(tensor, np.ndarray):
        return tensor
    try:
        import ttnn
    except ImportError:
        ttnn = None
    if ttnn is not None and isinstance(tensor, ttnn.Tensor):
        tensor = ttnn.to_torch(tensor)
    if hasattr(tensor, "detach") and hasattr(tensor, "cpu"):
        import torch

        t = tensor.detach().cpu()
        if t.dtype == torch.bfloat16:
            return t.float().numpy()
        try:
            return t.numpy()
        except TypeError:  # torch.uint16 / uint32 on older numpy bridges
            target = {torch.uint16: np.uint16, torch.uint32: np.uint32}.get(t.dtype, np.int64)
            return t.to(torch.int64).numpy().astype(target)
    return np.asarray(tensor)


def host_view(tensor: Any) -> Optional[np.ndarray]:
    """Zero-copy numpy view of a ROW_MAJOR ttnn HOST tensor's buffer (single-device shard 0), with the tensor's
    logical shape and ``to_numpy``'s dtype; the view keeps the buffer alive. None when the tensor is not ROW_MAJOR,
    its dtype has no exact numpy view (bf16 / bfp8 / ...), its buffer is padded, or the runtime has no
    ``host_buffer()`` dlpack bridge (callers then use :func:`to_numpy`). ttaw 0.24.2 (METEOR OPT2 round 5)."""
    try:
        import ttnn

        if tensor.layout != ttnn.ROW_MAJOR_LAYOUT:
            return None
        npdt = {ttnn.float32: np.float32, ttnn.uint32: np.uint32, ttnn.int32: np.int32,
                ttnn.uint16: np.uint16, ttnn.uint8: np.uint8}.get(tensor.dtype)
        if npdt is None:
            return None
        shape = tuple(int(v) for v in tensor.shape)
        if tuple(int(v) for v in tensor.padded_shape) != shape:
            return None
        raw = np.from_dlpack(tensor.host_buffer().get_shard(ttnn.MeshCoordinate(0, 0)).__array__())
        v = raw.reshape(-1).view(npdt)
        if v.size != int(np.prod(shape)):
            return None
        return v.reshape(shape)
    except Exception:  # noqa: BLE001 - any missing bridge / fake runtime: the copy path
        return None


def to_layout(tensor, layout):
    """``ttnn.to_layout`` that returns the input unchanged when it already has ``layout`` (no extra program)."""
    import ttnn

    return tensor if tensor.layout == layout else ttnn.to_layout(tensor, layout)


def typecast(tensor, dtype):
    """``ttnn.typecast`` that is a no-op when ``tensor`` already has ``dtype``."""
    import ttnn

    dtype = ttnn_dtype(dtype)
    return tensor if tensor.dtype == dtype else ttnn.typecast(tensor, dtype)


def to_fp32(tensor):
    """Enter an fp32 island (typecast to FLOAT32 if needed)."""
    return typecast(tensor, "float32")


def to_bf16(tensor):
    """Leave an fp32 island (typecast to BFLOAT16 if needed)."""
    return typecast(tensor, "bfloat16")


def fp32_island(fn: Callable[..., Any], *tensors, out_dtype: Any = "bfloat16"):
    """Run ``fn`` on fp32 copies of ``tensors`` and cast its tensor output(s) to ``out_dtype`` (``None`` keeps
    fp32). For numerically sensitive glue (box coding, softmax logits, geometry) between bf16 stages."""
    out = fn(*(to_fp32(t) for t in tensors))
    if out_dtype is None:
        return out
    if isinstance(out, (list, tuple)):
        return type(out)(typecast(t, out_dtype) for t in out)
    return typecast(out, out_dtype)


def upload_u8(array: ArrayLike, device, *, out_dtype: Any = "bfloat16", layout: Any = None, memory_config: Any = None):
    """Upload uint8 data (4x less PCIe traffic than fp32) and typecast it on the device (exact for 0..255).

    In a traced model keep the uint8 tensor as the persistent trace input and make ``ttnn.typecast`` the first
    traced op; this helper is the eager form."""
    import ttnn

    layout = ttnn.ROW_MAJOR_LAYOUT if layout is None else layout
    u8 = ttnn.to_device(to_host_tensor(array, "uint8", layout), device,
                        memory_config=memory_config or ttnn.DRAM_MEMORY_CONFIG)
    return typecast(u8, out_dtype)


class HostStaging:
    """A persistent ROW_MAJOR host tensor written in place for every frame (RP section 2.11, rf-detr R3c).

    ``write(array)`` copies (and casts) into the tensor's own host buffer through a writable ``torch.from_dlpack``
    alias, so no ``ttnn.from_torch`` allocation happens per frame; ``.tensor`` is what you pass to
    ``ttnn.copy_host_to_device_tensor`` (or ``TraceRunner.run(inputs=...)``). bf16 is written as RNE-rounded bit
    patterns. If the alias check fails on some tt-metal build, ``zero_copy`` is ``False`` and ``write`` rebuilds the
    host tensor with ``from_torch`` (same result, slower)."""

    _VIEW = {"float32": np.float32, "bfloat16": np.uint16, "uint32": np.uint32, "int32": np.int32,
             "uint16": np.uint16, "uint8": np.uint8}

    def __init__(self, shape: Sequence[int], dtype: Any = "float32"):
        import torch
        import ttnn

        self.shape = tuple(int(s) for s in shape)
        self.dtype = ttnn_dtype(dtype)
        self._name = dtype_name(self.dtype)
        if self._name not in self._VIEW:
            raise ValueError(f"HostStaging supports {sorted(self._VIEW)}, not {self._name}")
        zeros = np.zeros(self.shape, _HOST_NUMPY[self._name])
        self.tensor = ttnn.from_torch(_exact_torch(zeros, self.dtype), dtype=self.dtype, layout=ttnn.ROW_MAJOR_LAYOUT)
        self.zero_copy = False
        self._keep: tuple = ()
        try:
            shard = self.tensor.host_buffer().get_shard(ttnn.MeshCoordinate(0, 0))
            raw = torch.from_dlpack(shard)
            view = raw.numpy().view(self._VIEW[self._name]).reshape(self.shape)
            probe = (np.arange(view.size) % 251 + 1).astype(view.dtype).reshape(self.shape)
            view[...] = probe
            back = to_numpy(self.tensor)
            expect = bf16_bits_to_float32(probe) if self._name == "bfloat16" else probe
            if np.array_equal(back.reshape(self.shape), expect):
                self.zero_copy = True
                self._keep = (shard, raw)
                self.view = view
            view[...] = 0
        except Exception:  # noqa: BLE001 -- API drift: fall back to from_torch per write
            self.zero_copy = False
        if not self.zero_copy:
            self.view = np.zeros(self.shape, self._VIEW[self._name])

    def write(self, array: ArrayLike):
        """Copy ``array`` (broadcastable to ``shape``) into the host buffer and return the host tensor."""
        a = np.asarray(array)
        if self._name == "bfloat16":
            self.view[...] = float32_to_bf16_bits(np.broadcast_to(a, self.shape))
        else:
            self.view[...] = np.broadcast_to(a, self.shape).astype(self.view.dtype, copy=False)
        if not self.zero_copy:
            import ttnn

            data = bf16_bits_to_float32(self.view) if self._name == "bfloat16" else self.view
            self.tensor = ttnn.from_torch(_exact_torch(data, self.dtype), dtype=self.dtype,
                                          layout=ttnn.ROW_MAJOR_LAYOUT)
        return self.tensor

    @property
    def nbytes(self) -> int:
        return int(math.prod(self.shape) * self.view.dtype.itemsize)