Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ test-h13-parity: $(BUILD)/mil-hwxc
test-h14-parity: $(BUILD)/mil-hwxc
python3 research/generate_h14_templates.py --check
python3 tests/test_h14_parity.py $(BUILD)/mil-hwxc
python3 tests/test_h14_linked_reuse_oracles.py
python3 tests/test_h14_fixture_programs.py $(BUILD)/mil-hwxc
python3 tests/test_h14_matvec_programs.py $(BUILD)/mil-hwxc
python3 tests/test_h14_matvec_row_programs.py $(BUILD)/mil-hwxc
Expand Down
23 changes: 18 additions & 5 deletions docs/ane/h14-conv.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,10 @@ alignment. Word 0 contains its own word count in bits 26–16 and TID in
15–0. There is no NextPointer, NextSize, H13 continuation/end flag, or ninth
DTID word. Word 6 is LiveOuts; word 7 holds TSR bit 0 and engine selection.
In particular, copying H13 TSE/TSR (`0x9000`) into word 6 would corrupt
LiveOuts. The independent generic tasks close their live-outs and keep the
observed H14 TSR form `0x50001`; the consumer's DMA dependency supplies the
DRAM hand-off.
LiveOuts. Single-task layers close their live-outs and keep the observed H14
TSR form `0x50001`; the consumer's DMA dependency supplies the DRAM hand-off.
Every task of a multi-task layer keeps LiveOuts `0x1fffffff`, except the
program's last task, as in Apple's linked programs.

A dense BAR record has bit 29 set, and BAR slot in bits 28–23. The native
convolution records bind slot 1 to constants, slot 4 to input and slot 5 to
Expand All @@ -71,8 +72,20 @@ H13 header selector. Every intermediate gets a separate 16-KiB-aligned
region. No region is reused.

On each layer's first task after the first layer, the source config sets
DependencyMode 1 (`0x10000000`). Further output slices read the same region
with DependencyMode 0. Scratch readers use the decoded low config `0xe41`
DependencyMode 1 (`0x10000000`). Further output slices of a multi-task layer
do not read the input again. They reuse what the first slice staged in L2,
which is the form Apple emits for every decoded multi-task layer
(`chain3_c1024_s28` tasks 1-3 and 6-8, and the stride-2 consumer of
`h14_s2link_pw1024_pws2_2048`, tasks 5-9, both in research/oracles/h14-mobile).
Such a task has no source TileDMA records and no `0x504`/`0x514`/`0x518` words, its NE repeat fields (`0x38` bits 15:8)
take the NE class, and ResultCfg (`0x530`) drops the DMA-source bits
`0x500030`. Before this, a second slice reloaded the input from scratch DRAM
with DependencyMode 0. On the M2 that slice computed on zeros at MobileNet
layer 9 (the first two-task consumer): its 128 channels equalled relu(bias)
while the first slice was correct, although the same two tasks are correct
when they read the program input. With the reuse form both slices match the
CPU (rel. L2 5.5e-4) and the whole linked MobileNetV1 agrees on top-1 for
16/16 images at 1.13 to 1.21 ms p50 (01/11/2026, 7.3.0-aurora-tt3). Scratch readers use the decoded low config `0xe41`
and extension `0x4e`; scratch writers use cache hint `0xf`, producing
`0x01000ef1` in the ordinary output mode. The fresh `chain2_c128_s112` and
`chain3_c512_s56` probes exhibit these exact settings. Per-DMA task tags in
Expand Down
86 changes: 81 additions & 5 deletions plugins/H14/H14ConvGeneric.inc
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,76 @@ void fuseConvRelu(Program &p) {
}
}

// Later output slices of a multi-task layer reuse the input the layer's
// first task staged in L2, as Apple's linked H14 programs do (decoded
// chain3_c1024_s28 tasks 1-3 and 6-8, and the stride-2 consumer of
// h14_s2link_pw1024_pws2_2048, tasks 5-9). Such a task carries no source TileDMA
// records and no SourceCfg/depth-stride words (0x504, 0x514, 0x518). Its
// NE repeat fields (0x38 bits 15:8) take the NE class and ResultCfg (0x530)
// drops the bits a DMA-loaded source sets (0x500030). The task must be the
// last one in the stream.
void reuseLayerInput(Program &p, std::size_t off, std::size_t &bytes) {
if (off + bytes != p.taskStream.size())
throw std::logic_error("H14 input reuse requires the final task");
const auto ne = get(p, off, bytes, 0x38);
const auto cls = (ne >> 16) & 0xfu;
const auto resultCfg = get(p, off, bytes, 0x530) & ~0x500030u;
const std::size_t extra = (loadLE32(p.taskStream, off + 28) & 3) == 3 ? 4 : 0;
std::vector<std::uint8_t> out(p.taskStream.begin() + static_cast<std::ptrdiff_t>(off),
p.taskStream.begin() + static_cast<std::ptrdiff_t>(off + 32 + extra));
for (std::size_t c = off + 32 + extra; c < off + bytes;) {
const auto h = loadLE32(p.taskStream, c);
const auto base = (h & 0x7fff) * 4;
std::vector<std::uint32_t> addrs{base};
if (h & 0x80000000u) {
for (unsigned b = 0; b < 16; ++b)
if ((h >> (15 + b)) & 1) addrs.push_back(base + (b + 1) * 4);
} else {
for (std::uint32_t n = ((h >> 15) & 0x3f); n; --n)
addrs.push_back(addrs.back() + 4);
}
const auto end = c + (addrs.size() + 1) * 4;
const bool source = base >= 0x1100 && base < 0x1500;
if (source != (addrs.back() >= 0x1100 && addrs.back() < 0x1500))
throw std::logic_error("H14 record straddles the source TileDMA block");
if (source) { c = end; continue; }
const bool sourceCfg = std::any_of(addrs.begin(), addrs.end(), [](std::uint32_t a) {
return a == 0x504 || a == 0x514 || a == 0x518; });
if (!sourceCfg) {
out.insert(out.end(), p.taskStream.begin() + static_cast<std::ptrdiff_t>(c),
p.taskStream.begin() + static_cast<std::ptrdiff_t>(end));
c = end;
continue;
}
if (!(h & 0x80000000u))
throw std::logic_error("H14 input reuse expects the L2 words in a scatter record");
std::vector<std::pair<std::uint32_t, std::uint32_t>> kept;
for (std::size_t k = 0; k < addrs.size(); ++k) {
const auto a = addrs[k];
if (a == 0x504 || a == 0x514 || a == 0x518) continue;
kept.emplace_back(a, a == 0x530 ? resultCfg : loadLE32(p.taskStream, c + 4 + 4 * k));
}
if (!kept.empty()) {
const auto first = kept.front().first / 4;
std::uint32_t mask = 0;
for (std::size_t k = 1; k < kept.size(); ++k) {
const auto bit = kept[k].first / 4 - first - 1;
if (bit >= 16) throw std::logic_error("H14 L2 scatter record does not fit");
mask |= 1u << bit;
}
appendLE(out, 0x80000000u | (mask << 15) | first, 4);
for (const auto &kv : kept) appendLE(out, kv.second, 4);
}
c = end;
}
storeLE32(out, 0, (static_cast<std::uint32_t>(out.size() / 4) << 16) |
(loadLE32(out, 0) & 0xffff));
p.taskStream.resize(off);
p.taskStream.insert(p.taskStream.end(), out.begin(), out.end());
bytes = out.size();
put(p, off, bytes, 0x38, (ne & ~0xff00u) | (cls << 12) | (cls << 8));
}

Program linkConvChain(const std::vector<Program> &layers,
std::vector<LinkedLayer> *layout) {
if (layers.size() < 2) throw std::invalid_argument("h14.linked-outside-envelope: need at least two conv layers");
Expand Down Expand Up @@ -350,9 +420,11 @@ Program linkConvChain(const std::vector<Program> &layers,
p.taskStream.begin() + static_cast<std::ptrdiff_t>(src.first + src.second));
auto bytes = src.second;
auto set = [&](std::uint32_t a, std::uint32_t v) { put(result, off, bytes, a, v); };
const bool reuse = p.taskCount > 1 && i > 0;
if (reuse) reuseLayerInput(result, off, bytes);
set(0x1908, get(p, src.first, src.second, 0x1908) +
static_cast<std::uint32_t>(result.constants.size()));
if (l) {
if (l && !reuse) {
route(result, off, bytes, 0x1110, 3);
set(0x1110, static_cast<std::uint32_t>(regions[l - 1]));
// Native H14 scratch hints + dependency, not H13's 0x7bb81.
Expand All @@ -368,7 +440,8 @@ Program linkConvChain(const std::vector<Program> &layers,
if (result.taskCount >= 254)
throw std::invalid_argument("h14.linked-outside-envelope: DMA task-tag limit exceeded");
const auto tag = result.taskCount << 16;
set(0x1100, (get(result, off, bytes, 0x1100) & ~0xff0000u) | tag);
if (!reuse)
set(0x1100, (get(result, off, bytes, 0x1100) & ~0xff0000u) | tag);
set(0x1500, (get(result, off, bytes, 0x1500) & ~0xff0000u) | tag);
set(0x1900, (get(result, off, bytes, 0x1900) & ~0xff0000u) | ((result.taskCount + 1) << 16));
for (unsigned j = 0; j < 16; ++j)
Expand All @@ -377,9 +450,12 @@ Program linkConvChain(const std::vector<Program> &layers,
storeLE32(result.taskStream, off,
(static_cast<std::uint32_t>(bytes / 4) << 16) | result.taskCount);
storeLE32(result.taskStream, off + 8, (result.taskCount == 0 ? 8u : 0u) | (last ? 0x22u : 0u));
// LiveOuts closes at each independently loaded task, TSR remains
// set. H14 has no H13 header[6] TSE flag (it is LiveOuts).
storeLE32(result.taskStream, off + 24, 0);
// LiveOuts: every task of a multi-task layer keeps L2 live, as
// in Apple's linked programs, so later slices can reuse the
// staged input; single tasks and the program's last task close
// it. TSR remains set. H14 has no H13 header[6] TSE flag.
storeLE32(result.taskStream, off + 24,
p.taskCount > 1 && !last ? 0x1fffffffu : 0u);
storeLE32(result.taskStream, off + 28, 0x50001);
if (!result.taskCount) result.firstTaskBytes = bytes;
++result.taskCount;
Expand Down
83 changes: 83 additions & 0 deletions research/mint_h14_s2_chains.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Compile-only H14 chains whose consumer is a stride-2 or multi-task layer
reading its producer, on macOS. Retains decoded facts and hashes, like
mint_h14_mobile.py; the compiler is never asked to load or run a program.

These records show how Apple's compiler links a multi-task consumer: the first
slice loads the input (from scratch DRAM with DependencyMode 1, or from L2),
later slices carry no source TileDMA and reuse the staged input."""

import argparse
import hashlib
import json
import platform
import re
from pathlib import Path

import mint_conv_probes as conv
import mint_oracles as om
from mint_h14_mobile import compile_mil

# (kernel, input channels, output channels, input spatial, stride, groups),
# bias on, no relu.
CHAINS = {
'dw128_pws2_256': [(3, 128, 128, 56, 1, 128), (1, 128, 256, 56, 2, 1)],
'pw128_dw_pws2_256': [(1, 128, 128, 56, 1, 1), (3, 128, 128, 56, 1, 128),
(1, 128, 256, 56, 2, 1)],
'pws2_256_dw_pw': [(1, 128, 256, 56, 2, 1), (3, 256, 256, 28, 1, 256),
(1, 256, 256, 28, 1, 1)],
'dw512_pws2_1024': [(3, 512, 512, 14, 1, 512), (1, 512, 1024, 14, 2, 1)],
'pw512_pws2_2048': [(1, 512, 512, 28, 1, 1), (1, 512, 2048, 28, 2, 1)],
'pw1024_pws2_2048': [(1, 1024, 1024, 28, 1, 1), (1, 1024, 2048, 28, 2, 1)],
}


def chain_case(name, spec):
body, current, max_weights = [], 'x', 0
for i, (k, ci, co, sp, st, g) in enumerate(spec):
item = conv.conv_case(k, ci, co, sp, st, g, True)
text = item['mil'].split(') {\n', 1)[1].rsplit(' } ->', 1)[0]
for n in ('pt', 'st', 'pd', 'dl', 'gp', 'w', 'b', 'y'):
text = re.sub(r'\b' + n + r'\b', n + str(i), text)
text = text.replace('x = x)', 'x = ' + current + ')')
body.extend(text.strip().splitlines())
current = 'y' + str(i)
max_weights = max(max_weights, item['weights_description']['payload_bytes'])
k, ci, co, sp, st, g = spec[0]
return om.case(f'h14_s2link_{name}', 'h14_s2_link', dict(layers=spec),
om.program(f'{om.tensor_type((1, ci, sp, sp))} x', body, current),
om.blob(om.half_payload(max_weights // 2)),
dict(storage='BLOBFILE', value='fp16(0x1p-1)', payload_bytes=max_weights))


def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('--output', type=Path, default=Path(__file__).parent / 'oracles/h14-mobile')
ap.add_argument('--case')
ap.add_argument('--force', action='store_true')
args = ap.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
for name, spec in CHAINS.items():
item = chain_case(name, spec)
if args.case and args.case not in item['name']:
continue
out = args.output / (item['name'] + '.json')
if out.exists() and not args.force:
continue
record = dict(schema_version=1, case=item['name'], family=item['family'],
target='h14', source_commit=om.source_commit(),
parameters=item['parameters'], mil=item['mil'],
weights=item['weights_description'], compile_only=True,
compiler={'platform': platform.platform(), 'target': 'H14',
'driver_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest()})
try:
record.update(compile_mil(item['mil'], item['weights']))
record['error'] = None
except Exception as exc:
record['error'] = str(exc)
out.write_text(json.dumps(record, indent=2, sort_keys=True) + '\n')
print(out.name, 'tasks', len(record.get('task_descriptors') or []), record['error'])


if __name__ == '__main__':
main()
Loading