diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 8b73cd9a8..827bd2585 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -555,8 +555,9 @@ jobs: pattern: devkit-libs-* path: ${{ runner.temp }}/devkit-libs + # An empty plan succeeds without uploading devkit-xclbins. - name: Download the dev-kit kernels - if: needs.devkit-xclbins.result == 'success' + if: needs.devkit-xclbins.result == 'success' && needs.devkit-xclbins.outputs.empty != 'true' uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: devkit-xclbins diff --git a/.github/workflows/devkit-xclbins.yml b/.github/workflows/devkit-xclbins.yml index 66822df73..0db1ebfe4 100644 --- a/.github/workflows/devkit-xclbins.yml +++ b/.github/workflows/devkit-xclbins.yml @@ -86,6 +86,12 @@ on: mode changed the users of a kernel whose source changed and the models whose assignment changed; planned-models otherwise). value: ${{ jobs.plan.outputs.bench-models }} + empty: + description: > + "true" when the plan has nothing to build (say, a change that only + deletes a unit): build and assemble skip, no devkit-xclbins + artifact is uploaded, and the call still succeeds. + value: ${{ jobs.plan.outputs.empty }} workflow_dispatch: inputs: mode: diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/Makefile b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/Makefile deleted file mode 100644 index c4cd3ba95..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -# Portions of this file consist of AI-generated content. -# -# Inkling-2-Mini decode overlay. make kernel | bitstream | host - -include makefiles/common.mk -HOME_DIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST)))) - -include makefiles/kernel.mk -include makefiles/bitstream.mk -include makefiles/host.mk - -.PHONY: all kernel bitstream host clean clean_all -all: bitstream host -kernel: ${KERNEL_OBJS} -bitstream: ${XCLBIN_TARGETS} -host: ${HOST_C_TARGET} - -clean: - -@rm -rf build/host ${HOST_C_TARGET} - -clean_all: - -@rm -rf build *.exe diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/check_routes.py b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/check_routes.py deleted file mode 100644 index f112fdc38..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/check_routes.py +++ /dev/null @@ -1,193 +0,0 @@ -#!/usr/bin/env python3 -# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -# Portions of this file consist of AI-generated content. - -"""Routing check for the routed design (input_physical.mlir) of the Inkling-2-Mini decode overlay, run after every xclbin build. - -The packet-switched network can deadlock in ways the compiler does not see: a -switch arbiter carries one packet at a time from start to end, so a packet that -stalls halfway (its receiver is full) blocks every other flow on that arbiter, -even ones leaving through other ports. If the stalled flow is waiting for one of -those blocked flows, nothing moves again. Seen on hardware with the old x relay -design (rms -> relay packets vs MT1's per-column x packets, and proj outputs vs -those x packets). - -The check traces every packet flow hop by hop through the switch rules and fails if - 1. a flow does not arrive exactly where it was asked to, or - 2. two flows from FORBIDDEN_PAIRS groups share an arbiter in some switch. - -Usage: check_routes.py (exit 1 on a problem) - The routed file has the switch settings; the generated MLIR lists the flows asked - for (routing turns circuit flows into plain switch connections). -""" -import re -import sys -from collections import defaultdict - -# ---- flow groups (none yet: no wait loops between packet flows in the overlay) ---- -GROUPS = {} -X_ONLY_WITH = () -FORBIDDEN_PAIRS = [] -WARN_PAIRS = [] - -# ---- parse ------------------------------------------------------------------------ -text = open(sys.argv[1]).read() -tile_xy = {m.group(1): (int(m.group(2)), int(m.group(3))) - for m in re.finditer(r"%(\w+)\s*=\s*aie\.tile\((\d+),\s*(\d+)\)", text)} - -def blocks(kind): - """Bodies of aie.(%tile) { ... }, brace matched.""" - for m in re.finditer(r"aie\.%s\(%%(\w+)\)\s*\{" % kind, text): - depth, i = 1, m.end() - while depth: - depth += {"{": 1, "}": -1}.get(text[i], 0) - i += 1 - yield tile_xy[m.group(1)], text[m.end():i - 1] - -port = lambda s: tuple(x.strip() for x in s.split(":")) # "East : 2" -> ("East", "2") -switch = {} # xy -> (rules, amsel masters, amsel arbiter, connects) -for xy, body in blocks("switchbox"): - masters = defaultdict(list) - for m in re.finditer(r"aie\.masterset\(([^,]+:[^,]+),\s*([^)]*)\)", body): - for a in m.group(2).split(","): - masters[a.strip()].append(port(m.group(1))) - rules = defaultdict(list) - for m in re.finditer(r"aie\.packet_rules\(([^)]*)\)\s*\{(.*?)\}", body, re.S): - for r in re.finditer(r"aie\.rule\((\d+),\s*(\d+),\s*(%\w+)\)", m.group(2)): - rules[port(m.group(1))].append((int(r.group(1)), int(r.group(2)), r.group(3))) - arbiter = {m.group(1): int(m.group(2)) - for m in re.finditer(r"(%\w+)\s*=\s*aie\.amsel<(\d+)>\s*\((\d+)\)", body)} - connects = defaultdict(list) - for a, b in re.findall(r"aie\.connect<([^,]+),\s*([^>]+)>", body): - connects[port(a)].append(port(b)) - switch[xy] = (rules, masters, arbiter, connects) -shim_mux = {xy: [(port(a), port(b)) for a, b in re.findall(r"aie\.connect<([^,]+),\s*([^>]+)>", body)] - for xy, body in blocks("shim_mux")} - -STEP = {"East": (1, 0, "West"), "West": (-1, 0, "East"), "North": (0, 1, "South"), "South": (0, -1, "North")} - -def start_port(xy, ch, bundle="DMA"): - """Where a DMA MM2S channel (or a tile's control port) enters its switchbox (shim DMAs go through the mux).""" - if bundle == "TileControl": - return ("TileControl", str(ch)) - if xy[1] == 0: - for a, b in shim_mux.get(xy, []): - if a == ("DMA", str(ch)): - return ("South", b[1]) - return None - return ("DMA", str(ch)) - -def arrive(xy, mport): - """A master port that ends a flow: a DMA, or a shim's South into the mux.""" - if mport[0] in ("DMA", "TileControl"): - return (xy, mport[0], mport[1]) - if xy[1] == 0 and mport[0] == "South": - for a, b in shim_mux.get(xy, []): - if a == ("North", mport[1]): - return (xy, b[0], b[1]) - return None - -def next_hop(xy, mport): - if mport[0] in STEP: - dx, dy, back = STEP[mport[0]] - return (xy[0] + dx, xy[1] + dy), (back, mport[1]) - return None - -def trace_packet(xy, slave, pid, arbs, dests, depth=0): - if depth > 64 or xy not in switch: - return - rules, masters, arbiter, _ = switch[xy] - for mask, value, amsel in rules.get(slave, []): - if pid & mask == value & mask: # first matching rule wins - arbs.add((xy, arbiter.get(amsel))) - for mport in masters[amsel]: - hop = next_hop(xy, mport) - end = arrive(xy, mport) - if end: - dests.add(end) - elif hop: - trace_packet(hop[0], hop[1], pid, arbs, dests, depth + 1) - return - -def trace_circuit(xy, slave, dests, depth=0): - if depth > 64 or xy not in switch: - return - for mport in switch[xy][3].get(slave, []): - end = arrive(xy, mport) - hop = next_hop(xy, mport) - if end: - dests.add(end) - elif hop: - trace_circuit(hop[0], hop[1], dests, depth + 1) - -# ---- what was asked (from the generated MLIR) ------------------------------------------ -asked = open(sys.argv[2]).read() -asked_xy = {m.group(1): (int(m.group(2)), int(m.group(3))) - for m in re.finditer(r"%(\w+)\s*=\s*aie\.tile\((\d+),\s*(\d+)\)", asked)} -want_packet = defaultdict(set) -for m in re.finditer(r"aie\.packet_flow\((\d+)\)\s*\{(.*?)\n\s*\}", asked, re.S): - srcs = re.findall(r"packet_source<%(\w+),\s*(\w+)\s*:\s*(\d+)>", m.group(2)) - dsts = re.findall(r"packet_dest<%(\w+),\s*(\w+)\s*:\s*(\d+)>", m.group(2)) - for s in srcs: - for d in dsts: - want_packet[(asked_xy[s[0]], s[1], int(s[2]), int(m.group(1)))].add((asked_xy[d[0]], d[1], d[2])) -want_circuit = defaultdict(set) -for s, sb, sc, d, db, dc in re.findall(r"aie\.flow\(%(\w+),\s*(\w+)\s*:\s*(\d+),\s*%(\w+),\s*(\w+)\s*:\s*(\d+)\)", asked): - want_circuit[(asked_xy[s], sb, int(sc))].add((asked_xy[d], db, dc)) - -# ---- check ------------------------------------------------------------------------ -problems, warnings = [], [] -arb_users = defaultdict(set) -for key, want in sorted(want_packet.items()): - xy, bundle, ch, pid = key - if bundle not in ("DMA", "TileControl"): - continue - arbs, dests = set(), set() - sp = start_port(xy, ch, bundle) - if sp: - trace_packet(xy, sp, pid, arbs, dests) - want_dma = {w for w in want if w[1] in ("DMA", "TileControl")} # control packets to and from tile control ports too - got_dma = {d for d in dests if d[1] in ("DMA", "TileControl")} - if got_dma != want_dma: - problems.append(f"packet flow src {xy} ch{ch} id{pid}: asked {sorted(want_dma)}, routed to {sorted(got_dma)}") - for a in arbs: - arb_users[a].add(key[:1] + key[2:]) # (xy, ch, pid) -for key, want in sorted(want_circuit.items()): - xy, bundle, ch = key - if bundle != "DMA": - continue - dests = set() - sp = start_port(xy, ch) - if sp: - trace_circuit(xy, sp, dests) - want_dma = {w for w in want if w[1] == "DMA"} - if {d for d in dests if d[1] == "DMA"} != want_dma: - problems.append(f"circuit flow src {xy} ch{ch}: asked {sorted(want_dma)}, routed to {sorted(dests)}") - -for (xy, arb), users in sorted(arb_users.items(), key=lambda t: (t[0][0], t[0][1] or 0)): - groups = defaultdict(set) - for u in users: - for name, member in GROUPS.items(): - if member(*u): - groups[name].add(u) - for pairs, out in ((FORBIDDEN_PAIRS, problems), (WARN_PAIRS, warnings)): - for a, b in pairs: - if groups[a] and groups[b] and groups[a] != groups[b]: - out.append(f"switch {xy} arbiter {arb} shared by {a} {sorted(groups[a])} and {b} {sorted(groups[b])}") - # strict x_in rule: everything else on an x_in arbiter must be in X_ONLY_WITH - allowed = set().union(*(groups[g] for g in X_ONLY_WITH)) - # flows from the same DMA channel as an x_in flow are fine: a channel sends one - # packet at a time, so while its x packet is stalled it sends nothing else anyway - x_channels = {u[:2] for u in groups["x_in"]} - allowed |= {u for u in users if u[:2] in x_channels} - if groups["x_in"] and users - allowed: - problems.append(f"switch {xy} arbiter {arb} shared by x_in {sorted(groups['x_in'])} and {sorted(users - allowed)}") - -for w in warnings: - print("check_routes: WARNING " + w) -if problems: - print("check_routes: FAILED") - for p in problems: - print(" " + p) - sys.exit(1) -print(f"check_routes: OK ({len(want_packet)} packet flows, {len(want_circuit)} circuit flows)") diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/host/host.cpp b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/host/host.cpp deleted file mode 100644 index bdafbb677..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/host/host.cpp +++ /dev/null @@ -1,454 +0,0 @@ -// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -// Portions of this file consist of AI-generated content. -// -// Stand-alone test of the decode overlay's stream cores (kernel/decode_core.cc). -// run.exe sink [channels] [units] [tasks] [iters] shim -> core stream bandwidth -// run.exe gemv [channels] [groups] [nc] [tasks] [iters] Q4_K GEMV vs an fp32 reference, and its speed -// Channel c is shim MM2S (c / 8) of column c % 8, feeding core (c % 8, 2 + c / 8). - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "typedef.hpp" -#include "npu_utils/npu_utils.hpp" - -static constexpr int UNIT = 4736, X_OFF = 128, Y_UNIT = 96; -static constexpr npu_tiles IT[8] = {IT0, IT1, IT2, IT3, IT4, IT5, IT6, IT7}; - -static float bf2f(uint16_t v) { uint32_t u = (uint32_t)v << 16; float f; memcpy(&f, &u, 4); return f; } -static uint16_t f2bf(float f) { uint32_t u; memcpy(&u, &f, 4); u += 0x7FFF + ((u >> 16) & 1); return (uint16_t)(u >> 16); } - -// w[row][col] of one Q4_K block in q4k_to_npu order: w = q S sc + M mn -static void ref_block(float* w, const uint8_t* b) { - for (int H = 0; H < 2; H++) - for (int par = 0; par < 2; par++) { - const int hp = 2 * H + par; - for (int r = 0; r < 8; r++) { - const int row = 16 * H + 2 * r + par; - uint16_t Sv, Mv; - memcpy(&Sv, b + 4608 + hp * 16 + 2 * r, 2); - memcpy(&Mv, b + 4672 + hp * 16 + 2 * r, 2); - const float S = bf2f(Sv), M = bf2f(Mv); - for (int kt = 0; kt < 32; kt++) - for (int k = 0; k < 8; k++) { - const int g = kt / 4, i = r * 8 + k; - const uint8_t byte = b[512 + 2048 * H + 1024 * par + 32 * kt + i / 2]; - const int q = (i & 1) ? byte >> 4 : byte & 15; - w[row * 256 + 8 * kt + k] = q * (S * b[hp * 64 + g * 8 + r]) + M * b[256 + hp * 64 + g * 8 + r]; - } - } - } -} - -// hub core (kernel/hub.cc, iron/decode_aie.py) -static const npu_tiles HUB = get_tile(4, 0); -static constexpr uint32_t HUB_ARGS = 0x8200, HUB_START_LOCK = 0x1F000 + 16 * 10, SHIM_BD = 4, BASE_BD = 15; - -// The hub picks the streams: every channel holds two sink tasks (A, B: different bytes); the hub points the 16 -// channels at A or B (its extra offset) and pushes them. run.exe route [units] [iters] -static int route(int n, int iters, int dbg, int R) { - const int C = getenv("DEC_ROWS") && atoi(getenv("DEC_ROWS")) == 1 ? 8 : 16; // 8: the debug build, hub trace on - const bool tr_on = C == 8; - const int trw = getenv("TRW") ? atoi(getenv("TRW")) : 32; // trace words; with TRW set, wait on the trace only - const size_t task = (size_t)(1 + n) * UNIT, stride = 2 * task; - xrt::device dev(0); - npu_xclbin_manager mgr(npu_device::device_npu2, &dev, false); - npu_app_manager* am = mgr.register_xclbin("build/xclbins/decode.xclbin"); - npu_app apps[2] = {am->create_app(), am->create_app()}; - buffer in = apps[0].create_bo_buffer(16 * stride); - buffer out = apps[0].create_bo_buffer(16 * R * Y_UNIT); - buffer tr = apps[0].create_bo_buffer(64); - // ABS=1: the right data sits in another BO that is no run argument; the hub gets its device address - const bool abs_mode = getenv("ABS") && atoi(getenv("ABS")); - // CROSS=1: other is a 2040 MB BO (XRT sizes are int32) whose tasks sit across a 4 GB boundary of the device address - const bool cross = getenv("CROSS") != nullptr; - std::vector> spare; - buffer other = apps[0].create_bo_buffer(cross ? (size_t)2040 << 20 : 16 * stride); - size_t shift = 0; - for (int t = 0; cross; t++) { - const uint64_t dev = other.bo().address() + 0x80000000ull, next = (dev + 0xFFFFFFFFull) & ~0xFFFFFFFFull; - if (next - dev > 8 * stride && next - dev + 8 * stride < ((size_t)2040 << 20)) { - shift = next - dev - 8 * stride + 4096; - std::printf("other dev 0x%llx, shift %zu, boundary in task %zu\n", (unsigned long long)dev, shift, (size_t)(next - dev - shift) / stride); - break; - } - if (t == 4) { std::printf("no crossing BO\n"); return 3; } - spare.push_back(other); - other = apps[0].create_bo_buffer((size_t)2040 << 20); - } - for (int c = 0; c < 16; c++) - for (int v = 0; v < 2; v++) { - uint8_t* p = in.data() + c * stride + v * task; - memset(p, 0, UNIT); - ((int*)p)[0] = 1; ((int*)p)[1] = n; - for (int i = 1; i <= n; i++) p[(size_t)i * UNIT] = (uint8_t)(i * (v + 1) + c); - } - const bool abs_in = getenv("ABSIN") != nullptr; // ABS=1 ABSIN=1: absolute address of the run-argument BO itself - if (abs_mode && !abs_in) { - memcpy(other.data() + shift, in.data(), 16 * stride); - memset(in.data(), 0, 16 * stride); - other.sync_to_device(); // whole BO: slow for CROSS, fine for a probe - } - in.sync_to_device(); - const uint64_t oa = (abs_in ? in.bo().address() : other.bo().address()) + shift + (getenv("AOFF") ? strtoull(getenv("AOFF"), nullptr, 0) : 0); - std::printf("in BO at 0x%llx, other at 0x%llx\n", (unsigned long long)in.bo().address(), (unsigned long long)other.bo().address()); - if (abs_mode) std::printf("other BO at 0x%llx\n", (unsigned long long)oa); - for (int v = 0; v < 2; v++) { - npu_sequence* seq = apps[v].seq(); - seq->clear_cmds(); - if (tr_on) seq->npu_dma_memcpy_nd(4, 2, S2MM, IT0, npu_bd_id(6), it_channel_1, {0, 0, 0, 0}, {1, 1, 1, (uint32_t)trw}, {0, 0, 0, 1}); - // the hub reads the buffer address from this BD once (never started) - seq->npu_dma_memcpy_nd(1, 0, MM2S, IT0, npu_bd_id(BASE_BD), it_channel_0, {0, 0, 0, 0}, {1, 1, 1, 1}, {0, 0, 0, 1}, -1, 0, false, normal_cache, 15, false); - for (int c = 0; c < C; c++) { - const int col = c % 8, r = c / 8; - const npu_it_channel ch = r ? it_channel_1 : it_channel_0; - // the BD the hub patches: written here (address = the buffer), not started; in mode 0 it points at the - // other variant, so only the hub's patch gives the right sums - seq->npu_dma_memcpy_nd(1, 0, MM2S, IT[col], npu_bd_id(SHIM_BD + r), ch, {0, 0, 0, (uint32_t)(c * stride + (dbg ? v : 1 - v) * task)}, {1, 1, 1, (uint32_t)task}, {0, 0, 0, 1}, - -1, 0, false, normal_cache, 15, false); - if (getenv("SEQABS")) { // the sequence itself points the BD at an absolute address (raw register writes) and pushes it - const uint64_t a = oa + c * stride + v * task; - const uint32_t bda = 0x1D000u + (SHIM_BD + r) * 0x20u; - seq->rtp_write(IT[col], bda + 4, (uint32_t)a); - seq->npu_maskwrite(IT[col], bda + 8, (uint32_t)(a >> 32) & 0xFFFFu, 0xFFFFu); - seq->rtp_write(IT[col], r ? 0x1D21Cu : 0x1D214u, SHIM_BD + r); - } - seq->npu_dma_memcpy_nd(4, 1, S2MM, IT[col], npu_bd_id(2 + r), ch, {0, 0, 0, (uint32_t)(c * R * Y_UNIT)}, {1, 1, (uint32_t)R, (uint32_t)Y_UNIT}, {0, 0, (uint32_t)Y_UNIT, 1}); - } - seq->npu_maskwrite(HUB, 0x32038, 1, 1); - seq->rtp_write(HUB, HUB_ARGS + 0, (uint32_t)task); - seq->rtp_write(HUB, HUB_ARGS + 4, (uint32_t)stride); - seq->rtp_write(HUB, HUB_ARGS + 8, (uint32_t)(v * task)); - seq->rtp_write(HUB, HUB_ARGS + 12, (uint32_t)dbg); - seq->rtp_write(HUB, HUB_ARGS + 16, (uint32_t)tr_on); - seq->rtp_write(HUB, HUB_ARGS + 20, getenv("SEQABS") ? 0u : (uint32_t)C); - seq->rtp_write(HUB, HUB_ARGS + 24, (uint32_t)R); - seq->rtp_write(HUB, HUB_ARGS + 28, (uint32_t)abs_mode); - seq->rtp_write(HUB, HUB_ARGS + 32, (uint32_t)oa); - seq->rtp_write(HUB, HUB_ARGS + 36, (uint32_t)(oa >> 32)); - seq->rtp_write(HUB, HUB_START_LOCK, 1); - if (getenv("TRW")) seq->npu_dma_wait(IT0, S2MM, it_channel_1); - else for (int c = 0; c < C; c++) seq->npu_dma_wait(IT[c % 8], S2MM, c / 8 ? it_channel_1 : it_channel_0); - seq->cmds2seq(); - } - bool ok = true; - double us[2] = {}; - for (int it = 0; it < iters; it++) - for (int v = 0; v < 2; v++) { - for (int i = 0; i < 16 * R * Y_UNIT; i++) out.data()[i] = -1.0f; - out.sync_to_device(); - const auto t0 = std::chrono::steady_clock::now(); - if (tr_on) { - for (int i = 0; i < 64; i++) tr.data()[i] = 0xFFFFFFFF; - tr.sync_to_device(); - xrt::run run = apps[v].create_run(in, out, tr); - run.start(); - ert_cmd_state st = ERT_CMD_STATE_TIMEOUT; - try { st = run.wait(std::chrono::milliseconds(3000)); } catch (const std::exception& e) { std::printf("wait: %s\n", e.what()); } - tr.sync_from_device(); - std::printf("run state %d, trace:", (int)st); - for (int i = 0; i < 32 && tr.data()[i] != 0xFFFFFFFF; i++) std::printf(" %x", tr.data()[i]); - std::printf("\n"); - if (st != ERT_CMD_STATE_COMPLETED) return 2; - } else if (getenv("ABSARG")) { - apps[v](in, out, other); - } else { - apps[v](in, out); - } - us[v] += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - out.sync_from_device(); - for (int c = 0; c < C; c++) { - unsigned sum = 0; - for (int i = 1; i <= n; i++) sum += (uint8_t)(i * (v + 1) + c); - for (int q = 0; q < R; q++) { - const float* y = out.data() + (c * R + q) * Y_UNIT; - if (y[0] != n || y[1] != (float)sum) { - if (ok || getenv("ALLF")) std::printf("iter %d variant %d ch %d: %g %g (want %d %u)\n", it, v, c, y[0], y[1], n, sum); - ok = false; - } - } - } - } - const double bytes = (double)C * R * task; - std::printf("route n=%d: A %.1f us, B %.1f us per run (%.2f GB/s), check %s\n", n, us[0] / iters, us[1] / iters, - bytes / (us[1] / iters) / 1e3, ok ? "OK" : "FAIL"); - return ok ? 0 : 1; -} - -// A decode MoE call as the engine runs it: E of NX experts (each 24 groups of 96 rows x nc column blocks, the grouped -// layout) spread over the 16 channels in (expert, group) order. A channel's work is header tasks (x, from the io -// buffer) and weight tasks; arg 0 = io (headers, then y), args 1-4 = sub-buffers of the weight buffer at the chosen -// experts (per call), so the instruction sequence is fixed per E. shared_x: one x for all experts (gate_up), else -// one x per expert (down: h). run.exe experts [E] [nc] [shared_x] [iters] -static int experts(int E, int nc, bool shared_x, int iters) { - constexpr int NX = 8, GPE = 24, C = 16; - const size_t eb = (size_t)GPE * nc * 3 * UNIT; // bytes per expert - xrt::device dev(0); - npu_xclbin_manager mgr(npu_device::device_npu2, &dev, false); - npu_app_manager* am = mgr.register_xclbin("build/xclbins/decode.xclbin"); - npu_app app = am->create_app(); - buffer wt = app.create_bo_buffer(NX * eb); - std::mt19937 rng(7); - for (size_t b = 0; b < NX * eb / UNIT; b++) { - uint8_t* blk = wt.data() + b * UNIT; - for (int i = 0; i < UNIT; i++) blk[i] = (uint8_t)rng(); - for (int i = 0; i < 256; i++) { blk[i] &= 63; blk[256 + i] &= 63; } - for (int i = 0; i < 32; i++) { - uint16_t s = f2bf(0.0005f * (1 + (rng() % 1000) / 1000.0f)), m = f2bf(-0.004f * (rng() % 1000) / 1000.0f); - memcpy(blk + 4608 + 2 * i, &s, 2); - memcpy(blk + 4672 + 2 * i, &m, 2); - } - } - wt.sync_to_device(); - // the split: channel c takes groups [c * total / C, (c + 1) * total / C) of the (expert slot, group) order - struct seg { int slot, g0, n; }; - const int total = E * GPE; - std::vector> segs(C); - for (int c = 0; c < C; c++) { - int g = c * total / C; - const int end = (c + 1) * total / C; - while (g < end) { - const int s = g / GPE, n = std::min(end, (s + 1) * GPE) - g; - segs[c].push_back({s, g % GPE, n}); - g += n; - } - } - // io: header units [C][2], then y [C][groups][96] - const size_t hdr0 = 0, y0 = (size_t)C * 2 * UNIT; - std::vector ybase(C); - size_t yo = y0; - for (int c = 0; c < C; c++) { - ybase[c] = yo; - for (const seg& s : segs[c]) yo += (size_t)s.n * Y_UNIT * 4; - } - buffer io = app.create_bo_buffer(yo); - npu_sequence* seq = app.seq(); - seq->clear_cmds(); - for (int c = 0; c < C; c++) { - const int col = c % 8, r = c / 8; - const npu_it_channel ch = r ? it_channel_1 : it_channel_0; - int ny = 0; - for (const seg& s : segs[c]) ny += s.n; - seq->npu_dma_memcpy_nd(4, 0, S2MM, IT[col], npu_bd_id(14 + r), ch, {0, 0, 0, (uint32_t)(ybase[c] / 4)}, {1, 1, 1, (uint32_t)(ny * Y_UNIT)}, {0, 0, 0, 1}); - int bd = 6 * r; - for (size_t i = 0; i < segs[c].size(); i++) { - const seg& s = segs[c][i]; - if (i == 0 || !shared_x) - seq->npu_dma_memcpy_nd(1, 0, MM2S, IT[col], npu_bd_id(bd++), ch, {0, 0, 0, (uint32_t)(hdr0 + (size_t)(c * 2 + i) * UNIT)}, {1, 1, 1, (uint32_t)UNIT}, {0, 0, 0, 1}); - seq->npu_dma_memcpy_nd(1, 1 + s.slot, MM2S, IT[col], npu_bd_id(bd++), ch, {0, 0, 0, (uint32_t)((size_t)s.g0 * nc * 3 * UNIT)}, {1, 1, 1, (uint32_t)((size_t)s.n * nc * 3 * UNIT)}, {0, 0, 0, 1}); - } - } - for (int c = 0; c < C; c++) seq->npu_dma_wait(IT[c % 8], S2MM, c / 8 ? it_channel_1 : it_channel_0); - seq->cmds2seq(); - - std::vector chosen = {5, 2, 7, 0}; - std::vector> xs(E, std::vector(nc * 256)); - for (int e = 0; e < E; e++) - for (auto& v : xs[e]) v = f2bf(std::normal_distribution(0, 1)(rng)); - if (shared_x) for (int e = 1; e < E; e++) xs[e] = xs[0]; - auto fill_headers = [&] { - for (int c = 0; c < C; c++) { - int all = 0; - for (const seg& s : segs[c]) all += s.n; - for (size_t i = 0; i < segs[c].size(); i++) { - if (i > 0 && shared_x) break; - uint8_t* h = io.data() + hdr0 + (size_t)(c * 2 + i) * UNIT; - ((int*)h)[0] = 2; ((int*)h)[1] = shared_x ? all : segs[c][i].n; ((int*)h)[2] = nc; - memcpy(h + X_OFF, xs[segs[c][i].slot].data(), nc * 512); - } - } - }; - xrt::bo& wbo = wt.bo(); - double us = 0, part[7] = {}; - for (int it = 0; it <= iters; it++) { - for (size_t i = y0; i < io.size(); i += 4) *(float*)(io.data() + i) = -1.0f; - auto t0 = std::chrono::steady_clock::now(); - auto lap = [&](int k) { const auto t1 = std::chrono::steady_clock::now(); if (it > 0) part[k] += std::chrono::duration(t1 - t0).count(); t0 = t1; }; - fill_headers(); - lap(0); - io.sync_to_device(); - lap(1); - xrt::run run = app.create_run(io, wt, wt, wt, wt); - lap(2); - for (int s = 0; s < 4; s++) { - const size_t off = (size_t)chosen[std::min(s, E - 1)] * eb; - if (getenv("NOSUB")) continue; - run.set_arg(4 + s, xrt::bo(wbo, eb, off)); - } - lap(3); - run.start(); - lap(4); - run.wait(); - lap(5); - io.sync_from_device(); - lap(6); - } - for (int k = 0; k < 7; k++) us += part[k]; - std::printf("parts us: hdr %.1f sync %.1f create %.1f subbo %.1f start %.1f wait %.1f syncback %.1f\n", part[0] / iters, part[1] / iters, - part[2] / iters, part[3] / iters, part[4] / iters, part[5] / iters, part[6] / iters); - // check - double err2 = 0, ref2 = 0; - std::vector wb(32 * 256); - for (int c = 0; c < C; c++) { - const float* y = (const float*)(io.data() + ybase[c]); - for (const seg& s : segs[c]) - for (int g = 0; g < s.n; g++, y += Y_UNIT) { - double ref[96] = {}; - for (int cb = 0; cb < nc; cb++) - for (int b = 0; b < 3; b++) { - ref_block(wb.data(), wt.data() + chosen[s.slot] * eb + ((size_t)((s.g0 + g) * nc + cb) * 3 + b) * UNIT); - for (int row = 0; row < 32; row++) - for (int col = 0; col < 256; col++) ref[32 * b + row] += (double)wb[row * 256 + col] * bf2f(xs[s.slot][cb * 256 + col]); - } - for (int i = 0; i < 96; i++) { const double e = y[i] - ref[i]; err2 += e * e; ref2 += ref[i] * ref[i]; } - } - } - const double bytes = (double)E * eb; - std::printf("experts E=%d nc=%d shared_x=%d: %.1f us/call (%.2f GB/s), rel rms err %.3e\n", E, nc, (int)shared_x, us / iters, - bytes / (us / iters) / 1e3, std::sqrt(err2 / ref2)); - return std::sqrt(err2 / ref2) < 1e-2 ? 0 : 1; -} - -int main(int argc, char** argv) { - const std::string mode = argc > 1 ? argv[1] : "sink"; - if (mode == "experts") return experts(argc > 2 ? std::atoi(argv[2]) : 3, argc > 3 ? std::atoi(argv[3]) : 9, argc > 4 ? std::atoi(argv[4]) : 1, argc > 5 ? std::atoi(argv[5]) : 20); - if (mode == "route")return route(argc > 2 ? std::atoi(argv[2]) : 100, argc > 3 ? std::atoi(argv[3]) : 10, argc > 4 ? std::atoi(argv[4]) : 0, argc > 5 ? std::atoi(argv[5]) : 1); - const bool gemv = mode == "gemv"; - auto arg = [&](int i, int d) { return argc > i ? std::atoi(argv[i]) : d; }; - const int C = arg(2, 16); - const int G = gemv ? arg(3, 4) : 0, nc = gemv ? arg(4, 9) : 0; - const int n = gemv ? 0 : arg(3, 2000); - const int T = gemv ? arg(5, 1) : arg(4, 1); - const int iters = gemv ? arg(6, 20) : arg(5, 20); - - const int x_units = gemv ? (X_OFF + nc * 512 + UNIT - 1) / UNIT : 1; - const int task_units = gemv ? x_units + G * nc * 3 : 1 + n; - const int y_units = gemv ? G : 1; - const size_t ch_bytes = (size_t)T * task_units * UNIT; - - xrt::device dev(0); - npu_xclbin_manager mgr(npu_device::device_npu2, &dev, false); - npu_app_manager* am = mgr.register_xclbin("build/xclbins/decode.xclbin"); - npu_app app = am->create_app(); - buffer in = app.create_bo_buffer(ch_bytes * C); - buffer out = app.create_bo_buffer((size_t)C * T * y_units * Y_UNIT); - - std::mt19937 rng(1); - std::vector xs(nc * 256); - for (int c = 0; c < C; c++) - for (int t = 0; t < T; t++) { - uint8_t* p = in.data() + c * ch_bytes + (size_t)t * task_units * UNIT; - memset(p, 0, (size_t)x_units * UNIT); - int* h = (int*)p; - if (!gemv) { h[0] = 1; h[1] = n; for (int i = 1; i <= n; i++) p[(size_t)i * UNIT] = (uint8_t)(i + c); continue; } - h[0] = 2; h[1] = G; h[2] = nc; - uint16_t* x = (uint16_t*)(p + X_OFF); - for (int i = 0; i < nc * 256; i++) x[i] = f2bf(std::normal_distribution(0, 1)(rng)); - uint8_t* w = p + (size_t)x_units * UNIT; - for (size_t i = 0; i < (size_t)G * nc * 3 * UNIT; i++) w[i] = (uint8_t)rng(); - for (int b = 0; b < G * nc * 3; b++) { - uint8_t* blk = w + (size_t)b * UNIT; - for (int i = 0; i < 256; i++) { blk[i] &= 63; blk[256 + i] &= 63; } - for (int i = 0; i < 32; i++) { - uint16_t s = f2bf(0.0005f * (1 + (rng() % 1000) / 1000.0f)), m = f2bf(-0.004f * (rng() % 1000) / 1000.0f); - memcpy(blk + 4608 + 2 * i, &s, 2); - memcpy(blk + 4672 + 2 * i, &m, 2); - } - } - } - in.sync_to_device(); - for (size_t i = 0; i < out.size(); i++) out.data()[i] = -1.0f; - out.sync_to_device(); - - const cache_flag_t cache = getenv("DEC_CACHE") ? (cache_flag_t)atoi(getenv("DEC_CACHE")) : normal_cache; - npu_sequence* seq = app.seq(); - seq->clear_cmds(); - for (int t = 0; t < T; t++) { - for (int c = 0; c < C; c++) { - const int col = c % 8, r = c / 8; - const npu_it_channel ch = r ? it_channel_1 : it_channel_0; - seq->npu_dma_memcpy_nd(4, 1, S2MM, IT[col], npu_bd_id(2 + r), ch, - {0, 0, 0, (uint32_t)(((size_t)c * T + t) * y_units * Y_UNIT)}, {1, 1, 1, (uint32_t)(y_units * Y_UNIT)}, {0, 0, 0, 1}); - seq->npu_dma_memcpy_nd(1, 0, MM2S, IT[col], npu_bd_id(r), ch, - {0, 0, 0, (uint32_t)(c * ch_bytes + (size_t)t * task_units * UNIT)}, {1, 1, 1, (uint32_t)(task_units * UNIT)}, {0, 0, 0, 1}, -1, 0, false, cache); - } - for (int c = 0; c < C; c++) seq->npu_dma_wait(IT[c % 8], S2MM, c / 8 ? it_channel_1 : it_channel_0); - } - seq->cmds2seq(); - - app(in, out); // warm-up - const auto t0 = std::chrono::steady_clock::now(); - for (int i = 0; i < iters; i++) app(in, out); - const double us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / iters; - out.sync_from_device(); - const double bytes = (double)ch_bytes * C; - std::printf("%s C=%d task_units=%d T=%d: %.1f us/run, %.2f GB/s (%.2f GB/s per channel), %.2f us/task\n", mode.c_str(), C, - task_units, T, us, bytes / us / 1e3, bytes / us / 1e3 / C, us / T); - - if (!gemv) { - bool ok = true; - for (int c = 0; c < C; c++) - for (int t = 0; t < T; t++) { - const float* y = out.data() + ((size_t)c * T + t) * Y_UNIT; - unsigned sum = 0; - for (int i = 1; i <= n; i++) sum += (uint8_t)(i + c); - if (y[0] != n || y[1] != (float)sum) { ok = false; std::printf("ch %d task %d: %g %g (want %d %u)\n", c, t, y[0], y[1], n, sum); } - } - std::printf("sink check %s\n", ok ? "OK" : "FAIL"); - return ok ? 0 : 1; - } - double max_rel = 0, err2 = 0, ref2 = 0; - std::vector wb(32 * 256); - for (int c = 0; c < C; c++) - for (int t = 0; t < T; t++) { - const uint8_t* p = in.data() + c * ch_bytes + (size_t)t * task_units * UNIT; - const uint16_t* x = (const uint16_t*)(p + X_OFF); - const uint8_t* w = p + (size_t)x_units * UNIT; - const float* y = out.data() + ((size_t)c * T + t) * y_units * Y_UNIT; - for (int g = 0; g < G; g++) { - double ref[96] = {}; - for (int cb = 0; cb < nc; cb++) - for (int b = 0; b < 3; b++) { - ref_block(wb.data(), w + ((size_t)(g * nc + cb) * 3 + b) * UNIT); - for (int row = 0; row < 32; row++) - for (int col = 0; col < 256; col++) ref[32 * b + row] += (double)wb[row * 256 + col] * bf2f(x[cb * 256 + col]); - } - double scale = 0; - for (int i = 0; i < 96; i++) scale = std::max(scale, std::fabs(ref[i])); - for (int i = 0; i < 96; i++) { - const double e = y[g * 96 + i] - ref[i]; - err2 += e * e; ref2 += ref[i] * ref[i]; - max_rel = std::max(max_rel, std::fabs(e) / scale); - if (c == 0 && t == 0 && g == 0 && (i < 4 || getenv("DEC_DIAG"))) std::printf("y[%d] npu %.6f ref %.6f\n", i, y[i], ref[i]); - } - } - } - if (getenv("DEC_DIAG")) { // first group's rows of block 0, cb 0: q x term and min term apart - const uint8_t* p = in.data(); - const uint16_t* x = (const uint16_t*)(p + X_OFF); - const uint8_t* b = p + (size_t)x_units * UNIT; - for (int row = 0; row < 8; row++) { - const int H = row / 16, par = row % 2, r = (row % 16) / 2, hp = 2 * H + par; - uint16_t Sv, Mv; - memcpy(&Sv, b + 4608 + hp * 16 + 2 * r, 2); - memcpy(&Mv, b + 4672 + hp * 16 + 2 * r, 2); - double qt = 0, mt = 0; - for (int col = 0; col < 256; col++) { - const int kt = col / 8, k = col % 8, g = kt / 4, i = r * 8 + k; - const uint8_t byte = b[512 + 2048 * H + 1024 * par + 32 * kt + i / 2]; - const int q = (i & 1) ? byte >> 4 : byte & 15; - qt += q * bf2f(Sv) * b[hp * 64 + g * 8 + r] * bf2f(x[col]); - mt += bf2f(Mv) * b[256 + hp * 64 + g * 8 + r] * bf2f(x[col]); - } - std::printf("row %d: npu %.5f q-term %.5f min-term %.5f\n", row, out.data()[row], qt, mt); - } - } - std::printf("gemv rel rms err %.3e, max err / max |y| %.3e\n", std::sqrt(err2 / ref2), max_rel); - return 0; -} diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/iron/decode_aie.py b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/iron/decode_aie.py deleted file mode 100644 index fbbbf0615..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/iron/decode_aie.py +++ /dev/null @@ -1,167 +0,0 @@ -# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -# Portions of this file consist of AI-generated content. -# -# Inkling-2-Mini decode overlay. Core rows 2 and 3 of every column are stream cores: shim MM2S channel r of column -# j feeds core (j, 2 + r) directly, one 4736-byte unit at a time (a Q4_K block; the stream is a sequence of units, -# each task starting with a header unit, see kernel/decode_core.cc), and the core's y units go back on shim S2MM -# channel r. 16 shim channels carry weights, the most the array has. - -import numpy as np - -from aie.extras.context import mlir_mod_ctx -import aie.dialects.aie as aie -try: # mlir-aie as pinned by CI - from aie.helpers.dialects.ext.scf import _for as range_ -except ImportError: # newer mlir-aie moved it - from aie.helpers.dialects.scf import _for as range_ - -from utils import connect_dma, core_link_kwargs, dma_bd_compat, generate_tile_map, lock_acquire, lock_release, NEW_LINK_API - -COLS = 8 -import os -STREAM_ROWS = int(os.environ.get("DEC_ROWS", "2")) # 1: debug build, shim S2MM 1 of column 0 takes the hub trace -UNIT = 4736 # bytes: one Q4_K block of 32 x 256 -RING = 4 # units in flight per core -Y_UNIT = 96 # floats: one row group (3 row blocks) -X_MAX = 3072 # bf16: the widest input (o proj) -STACK = 8192 # bytes: decode_core frame is ~3.6 KB - - -def stream_core(ct, unit_ty, y_ty, x_ty, acc_ty, xn_ty, xs_ty, xr_ty, ss_ty, fn): - w = [aie.buffer(ct.tile, unit_ty, name=f"w{i}_{ct.row}_{ct.col}") for i in range(RING)] - y = [aie.buffer(ct.tile, y_ty, name=f"y{i}_{ct.row}_{ct.col}") for i in range(2)] - x = aie.buffer(ct.tile, x_ty, name=f"x_{ct.row}_{ct.col}") - acc = aie.buffer(ct.tile, acc_ty, name=f"acc_{ct.row}_{ct.col}") - xn = aie.buffer(ct.tile, xn_ty, name=f"xn_{ct.row}_{ct.col}") - xs = aie.buffer(ct.tile, xs_ty, name=f"xs_{ct.row}_{ct.col}") - xr = aie.buffer(ct.tile, xr_ty, name=f"xr_{ct.row}_{ct.col}") - ss = aie.buffer(ct.tile, ss_ty, name=f"ss_{ct.row}_{ct.col}") - w_prod = aie.lock(ct.tile, lock_id=0, init=RING) - w_cons = aie.lock(ct.tile, lock_id=1, init=0) - y_prod = aie.lock(ct.tile, lock_id=2, init=2) - y_cons = aie.lock(ct.tile, lock_id=3, init=0) - - @aie.core(ct.tile, stack_size=STACK, **core_link_kwargs("decode_core.o")) - def core_body(): - for _ in range_(0xFFFFFFFF): - fn(*w, *y, x, acc, xn, xs, xr, ss) - - @aie.mem(ct.tile) - def mem_body(block): - aie.dma_start(channel_dir=aie.DMAChannelDir.S2MM, channel_index=1, dest=block[1], chain=block[1 + RING]) - for i in range(RING): - with block[1 + i]: - lock_acquire(w_prod, 1) - dma_bd_compat(w[i]) - lock_release(w_cons, 1) - aie.next_bd(block[1 + (i + 1) % RING]) - with block[1 + RING]: - aie.dma_start(channel_dir=aie.DMAChannelDir.MM2S, channel_index=0, dest=block[2 + RING], chain=block[4 + RING]) - for i in range(2): - with block[2 + RING + i]: - lock_acquire(y_cons, 1) - dma_bd_compat(y[i]) - lock_release(y_prod, 1) - aie.next_bd(block[2 + RING + (i + 1) % 2]) - with block[4 + RING]: - aie.EndOp() - - -HUB_COL, HUB_ROW = 0, 2 # CT index: core (0, 4) -HUB_OUT, HUB_IN, HUB_ARGS, HUB_TR = 0x8000, 0x8100, 0x8200, 0x8300 # fixed addresses: the host writes args -HUB_STACK = 4096 -# Control packet ids, hub -> shim j, and the read responses (kernel/hub.cc has the same table). Found by search: -# aiecc merges the rules of flows that leave a switch the same way into one mask/match pair, and the switch takes -# the first matching rule, so most id sets send some shims' packets the wrong way (check_routes.py catches it). -CTRL_IDS = [int(v) for v in os.environ.get("DEC_CTRL_IDS", "5,8,17,31,22,30,21,23").split(",")] -RESP_ID = int(os.environ.get("DEC_RESP_ID", "9")) - - -def hub_core(ct): - u32 = np.dtype[np.uint32] - out = aie.buffer(ct.tile, np.ndarray[(8,), u32], name="hub_out", address=HUB_OUT) - inp = aie.buffer(ct.tile, np.ndarray[(4,), u32], name="hub_in", address=HUB_IN) - args = aie.buffer(ct.tile, np.ndarray[(16,), np.dtype[np.int32]], name="hub_args", address=HUB_ARGS) - out_prod = aie.lock(ct.tile, lock_id=6, init=1) - out_cons = aie.lock(ct.tile, lock_id=7, init=0) - in_prod = aie.lock(ct.tile, lock_id=8, init=1) - in_cons = aie.lock(ct.tile, lock_id=9, init=0) - aie.lock(ct.tile, lock_id=10, init=0) # start, set by the host - tr = aie.buffer(ct.tile, np.ndarray[(4,), u32], name="hub_tr", address=HUB_TR) - tr_prod = aie.lock(ct.tile, lock_id=11, init=1) - tr_cons = aie.lock(ct.tile, lock_id=12, init=0) - ty = [np.ndarray[(8,), u32], np.ndarray[(4,), u32], np.ndarray[(16,), np.dtype[np.int32]], np.ndarray[(4,), u32]] - if NEW_LINK_API: - fn = aie.external_func("hub", ty, link_with="hub.o") - else: - fn = aie.external_func("hub", ty) - - @aie.core(ct.tile, stack_size=HUB_STACK, **core_link_kwargs("hub.o")) - def core_body(): - for _ in range_(0xFFFFFFFF): - fn(out, inp, args, tr) - - @aie.mem(ct.tile) - def mem_body(block): - aie.dma_start(channel_dir=aie.DMAChannelDir.S2MM, channel_index=1, dest=block[1], chain=block[2]) - with block[1]: - lock_acquire(in_prod, 1) - aie.dma_bd(inp, offset=0, len=1, bd_id=11) - lock_release(in_cons, 1) - aie.next_bd(block[1]) - with block[2]: - aie.dma_start(channel_dir=aie.DMAChannelDir.MM2S, channel_index=1, dest=block[3], chain=block[4]) - with block[3]: - lock_acquire(out_cons, 1) - aie.dma_bd(out, offset=0, len=1, bd_id=10) # length set per packet by the kernel - lock_release(out_prod, 1) - aie.next_bd(block[3]) - with block[4]: - aie.dma_start(channel_dir=aie.DMAChannelDir.MM2S, channel_index=0, dest=block[5], chain=block[6]) - with block[5]: - lock_acquire(tr_cons, 1) - aie.dma_bd(tr, offset=0, len=1) - lock_release(tr_prod, 1) - aie.next_bd(block[5]) - with block[6]: - aie.EndOp() - - -def design(): - with mlir_mod_ctx() as ctx: - @aie.device(aie.AIEDevice.npu2) - def device_body(): - IT, MT, CT = generate_tile_map(4 + 2, COLS) - unit_ty = np.ndarray[(UNIT,), np.dtype[np.uint8]] - y_ty = np.ndarray[(Y_UNIT,), np.dtype[np.float32]] - x_ty = np.ndarray[(X_MAX,), np.dtype[np.uint16]] - acc_ty = np.ndarray[(12 * 64,), np.dtype[np.float32]] - # one column block's prepared x: xnr 8 x 64 fp32, xs 8 x 8 bf16, xr 32 x 64 bf16; ss 16 x 64 bf16 - xn_ty = np.ndarray[(512,), np.dtype[np.float32]] - xs_ty = np.ndarray[(64,), np.dtype[np.uint16]] - xr_ty = np.ndarray[(2048,), np.dtype[np.uint16]] - ss_ty = np.ndarray[(1024,), np.dtype[np.uint16]] - args = [unit_ty] * RING + [y_ty] * 2 + [x_ty, acc_ty, xn_ty, xs_ty, xr_ty, ss_ty] - if NEW_LINK_API: - fn = aie.external_func("decode_core", args, link_with="decode_core.o") - else: - fn = aie.external_func("decode_core", args) - for j in range(COLS): - for r in range(STREAM_ROWS): - stream_core(CT[r][j], unit_ty, y_ty, x_ty, acc_ty, xn_ty, xs_ty, xr_ty, ss_ty, fn) - connect_dma(IT[j], CT[r][j], r, 1) - connect_dma(CT[r][j], IT[j], 0, r) - hub = CT[HUB_ROW][HUB_COL] - hub_core(hub) - for j in range(COLS): - aie.packetflow(pkt_id=CTRL_IDS[j], source=hub.tile, source_port=aie.WireBundle.DMA, source_channel=1, - dest=IT[j].tile, dest_port=aie.WireBundle.TileControl, dest_channel=0) - aie.packetflow(pkt_id=RESP_ID, source=IT[0].tile, source_port=aie.WireBundle.TileControl, source_channel=0, - dest=hub.tile, dest_port=aie.WireBundle.DMA, dest_channel=1) - if STREAM_ROWS == 1: - connect_dma(hub, IT[0], 0, 1) - print(ctx.module) - - -if __name__ == "__main__": - design() diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/iron/utils.py b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/iron/utils.py deleted file mode 100644 index 73c821f4d..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/iron/utils.py +++ /dev/null @@ -1,185 +0,0 @@ -# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -# Portions of this file consist of AI-generated content. - -import os as _os -# Mirrors the makefiles' ENABLE_CHESSCC switch, so the generated MLIR can carry -# Peano-only layout changes. -ENABLE_CHESSCC = _os.environ.get("ENABLE_CHESSCC", "0") == "1" -if ENABLE_CHESSCC: - raise SystemExit("dequant_mm_bfp16 is Peano only (the bfp16 block-vector streams and the pinned layout are not built with Chess)") - -from dataclasses import dataclass -from ml_dtypes import bfloat16 -from aie.extras.context import mlir_mod_ctx -from aie.dialects.aie import * -from aie.dialects.aiex import * -try: # mlir-aie as pinned by CI - from aie.helpers.dialects.ext.scf import _for as range_ -except ImportError: # newer mlir-aie moved it - from aie.helpers.dialects.scf import _for as range_ -import inspect -from aie.dialects import memref -from typing import Dict, Any, List, Optional -from aie.extras import types as T - -@dataclass -class tile_with_location: - tile: tile - row: int - col: int - -@dataclass -class dma_port: - tile: tile_with_location - channel: int - -# The mlir-aie API moved between the CI toolchain and newer ones; the design builds with both. -# newer: link_with lives on external_func and dma_bd takes sizes/strides/transfer_len; -# CI: link_with lives on the core and dma_bd takes dimensions/len. -NEW_LINK_API = "link_with" in inspect.signature(aie.external_func.__init__).parameters -NEW_DMA_BD_API = "transfer_len" in inspect.signature(aie.dma_bd).parameters - - -def core_link_kwargs(obj_name: str): - """kwargs for @aie.core that link the kernel object (empty on the newer API, where the - external_func declaration carries it).""" - return {} if NEW_LINK_API else {"link_with": obj_name} - - -class mlir_context: - def __init__(self): - self.data_tys = {} - self.funcs = {} - self.buffers = {} - self.parameters = {} - self.object_fifos = {} - self.packet_ids = {} - - def data_ty(self, name: str, shape: List[int], dtype: Any): - d_ty = np.ndarray[shape, dtype] - self.data_tys[name] = d_ty - if not hasattr(self, name): - setattr(self, name, d_ty) - else: - raise ValueError(f"Data type {name} already exists") - return d_ty - - def buffer(self, name: str, tile: tile_with_location, dtype: Any, use_write_rtp: bool = False): - new_buffer = aie.buffer(tile.tile, dtype, name = name, use_write_rtp = use_write_rtp) - self.buffers[name] = new_buffer - if not hasattr(self, name): - setattr(self, name, new_buffer) - else: - raise ValueError(f"Buffer {name} already exists") - - return new_buffer - - def func(self, name: str, inputs: List[Any]): - if NEW_LINK_API: - this_func = aie.external_func(name, inputs, link_with=f"{name}.o") - else: - this_func = aie.external_func(name, inputs) - self.funcs[name] = this_func - if not hasattr(self, name): - setattr(self, name, this_func) - else: - raise ValueError(f"Function {name} already exists") - return this_func - - def parameter(self, name: str, value: Any): - self.parameters[name] = value - if not hasattr(self, name): - setattr(self, name, value) - else: - raise ValueError(f"Parameter {name} already exists") - return value - - def object_fifo(self, name: str, src_tile: tile_with_location, dst_tile: tile_with_location | List[tile_with_location], depth: int, data_ty: Any, *args, **kwargs): - if isinstance(dst_tile, tile_with_location): - fifo = object_fifo(name, src_tile.tile, dst_tile.tile, depth, data_ty, *args, **kwargs) - else: - fifo = object_fifo(name, src_tile.tile, [t.tile for t in dst_tile], depth, data_ty, *args, **kwargs) - self.object_fifos[name] = fifo - if not hasattr(self, name): - setattr(self, name, fifo) - else: - raise ValueError(f"Object fifo {name} already exists") - return fifo - - - -def dma_mm2s_ch(ch: int): - return { - "source_port": WireBundle.DMA, - "source_channel": ch - } - -def dma_s2mm_ch(ch: int): - return { - "dest_port": WireBundle.DMA, - "dest_channel": ch - } - -def flow_mm2s_ch(ch: int): - return { - "source_bundle": WireBundle.DMA, - "source_channel": ch - } - -def flow_s2mm_ch(ch: int): - return { - "dest_bundle": WireBundle.DMA, - "dest_channel": ch - } - -def generate_tile_map(total_rows: int, total_cols: int) -> Tuple[List[tile_with_location], List[tile_with_location], List[List[tile_with_location]]]: - # Tile declarations - ShimTiles = [] - MemTiles = [] - cores = [] - for col in range(total_cols): - ShimTiles.append(tile_with_location(tile(col, 0), 0, col)) - MemTiles.append(tile_with_location(tile(col, 1), 0, col)) - - for row in range(total_rows - 2): - ComputeTilesRow = [] - for col in range(total_cols): - ComputeTilesRow.append(tile_with_location(tile(col, row + 2), row + 2, col)) - - cores.append(ComputeTilesRow) - - return ShimTiles, MemTiles, cores - -def connect_dma(src: tile_with_location, dst: tile_with_location, src_ch: int, dst_ch: int, pkt_id: int = -1, keep_pkt_header: bool = False): - if pkt_id < 0: - aie.flow(source = src.tile, **flow_mm2s_ch(src_ch), dest = dst.tile, **flow_s2mm_ch(dst_ch)) - else: - aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src_ch), dest = dst.tile, **dma_s2mm_ch(dst_ch), keep_pkt_header = keep_pkt_header) - -def connect_port(src: dma_port, dst: dma_port, pkt_id: int = -1, keep_pkt_header: bool = False): - if pkt_id < 0: - aie.flow(source = src.tile, **flow_mm2s_ch(src.channel), dest = dst.tile, **flow_s2mm_ch(dst.channel)) - else: - aie.packetflow(pkt_id = pkt_id, source = src.tile, **dma_mm2s_ch(src.channel), dest = dst.tile, **dma_s2mm_ch(dst.channel), keep_pkt_header = keep_pkt_header) - - -def lock_acquire(lock: Any, value: int): - aie.use_lock(lock, aie.LockAction.AcquireGreaterEqual, value = value) - -def lock_release(lock: Any, value: int): - aie.use_lock(lock, aie.LockAction.Release, value = value) - - -def dma_bd_compat(buffer, offset=None, len=None, dimensions=None): - """aie.dma_bd(buffer, offset=, len=, dimensions=[(size, stride), ...]) on either API.""" - if not NEW_DMA_BD_API: - kw = {} - if offset is not None: kw["offset"] = offset - if len is not None: kw["len"] = len - if dimensions: kw["dimensions"] = dimensions - return aie.dma_bd(buffer, **kw) - kw = {} - if dimensions: - kw["sizes"] = [d[0] for d in dimensions] - kw["strides"] = [d[1] for d in dimensions] - return aie.dma_bd(buffer, offset=offset, transfer_len=len, **kw) diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/aie_kernel_utils.h b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/aie_kernel_utils.h deleted file mode 100644 index c5314aa0b..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/aie_kernel_utils.h +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -// Portions of this file consist of AI-generated content. -// SPDX-License-Identifier: MIT - -#ifndef _AIE_KERNEL_UTILS_ -#define _AIE_KERNEL_UTILS_ - -#include -typedef bfloat16 bf16; - -#if defined(__chess__) -#define AIE_LOOP_UNROLL(x) [[chess::unroll_loop(x)]] -#define AIE_LOOP_UNROLL_FULL [[chess::unroll_loop()]] -#define AIE_LOOP_NO_UNROLL [[chess::no_unroll]] -#define AIE_LOOP_MIN_ITERATION_COUNT(x) [[chess::min_loop_count(x)]] -#define AIE_LOOP_MAX_ITERATION_COUNT(x) [[chess::max_loop_count(x)]] -#define AIE_LOOP_RANGE(a, ...) \ - [[chess::min_loop_count(a)]] __VA_OPT__( \ - [[chess::max_loop_count(__VA_ARGS__)]]) -#define AIE_PREPARE_FOR_PIPELINING [[chess::prepare_for_pipelining]] -#define AIE_NO_PREPARE_FOR_PIPELINING [[chess::no_prepare_for_pipelining]] -#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) \ - [[chess::modulo_scheduling_budget_ratio(x)]] -#define AIE_KEEP_SW_LOOP [[chess::keep_sw_loop]] -#define AIE_PEEL_PIPELINED_LOOP(x) [[chess::peel_pipelined_loop(x)]] -#define AIE_KEEP_FREE_FOR_PIPELINING(x) [[chess::keep_free_for_pipelining(x)]] -#define AIE_ALLOCATE(x) [[chess::allocate(x)]] -#define AIE_NO_HW_LOOP [[chess::no_hw_loop]] -#define AIE_TRY_INITIATION_INTERVAL(x) -#define AIE_PREPARE_FOR_POSTPIPELINING -#define AIE_LOOP_FLATTEN chess_flatten_loop - -#elif defined(__AIECC__) -#ifndef __STRINGIFY -#define __STRINGIFY(a) #a -#endif -#define AIE_LOOP_UNROLL(x) _Pragma(__STRINGIFY(clang loop unroll_count(x))) -#define AIE_LOOP_UNROLL_FULL _Pragma("clang loop unroll(full)") -#define AIE_LOOP_NO_UNROLL _Pragma("clang loop unroll(disable)") -#define AIE_LOOP_MIN_ITERATION_COUNT(x) \ - _Pragma(__STRINGIFY(clang loop min_iteration_count(x))) -#define AIE_LOOP_MAX_ITERATION_COUNT(x) \ - _Pragma(__STRINGIFY(clang loop max_iteration_count(x))) -#define AIE_LOOP_RANGE(a, ...) \ - AIE_LOOP_MIN_ITERATION_COUNT(a) \ - __VA_OPT__(AIE_LOOP_MAX_ITERATION_COUNT(__VA_ARGS__)) -#define AIE_PREPARE_FOR_PIPELINING -#define AIE_NO_PREPARE_FOR_PIPELINING -#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) -#define AIE_KEEP_SW_LOOP -#define AIE_PEEL_PIPELINED_LOOP(x) -#define AIE_KEEP_FREE_FOR_PIPELINING(x) -#define AIE_ALLOCATE(x) -#define AIE_NO_HW_LOOP -#define AIE_TRY_INITIATION_INTERVAL(x) \ - _Pragma(__STRINGIFY(clang loop pipeline_initiation_interval(x))) -#define AIE_PREPARE_FOR_POSTPIPELINING _Pragma("clang loop pipeline(disable)") -#define AIE_LOOP_FLATTEN - -#else -#define AIE_LOOP_UNROLL(x) -#define AIE_LOOP_UNROLL_FULL -#define AIE_LOOP_NO_UNROLL -#define AIE_LOOP_MIN_ITERATION_COUNT(x) -#define AIE_LOOP_MAX_ITERATION_COUNT(x) -#define AIE_LOOP_RANGE(a, ...) -#define AIE_PREPARE_FOR_PIPELINING -#define AIE_NO_PREPARE_FOR_PIPELINING -#define AIE_MODULO_SCHEDULING_BUDGET_RATIO(x) -#define AIE_KEEP_SW_LOOP -#define AIE_PEEL_PIPELINED_LOOP(x) -#define AIE_KEEP_FREE_FOR_PIPELINING(x) -#define AIE_ALLOCATE(x) -#define AIE_NO_HW_LOOP -#define AIE_TRY_INITIATION_INTERVAL(x) -#define AIE_PREPARE_FOR_POSTPIPELINING -#define AIE_LOOP_FLATTEN -#endif - -// Some lock utilities -/// \brief Acquire a lock with given lock ID on this CT and number of locks -/// \param lock_id The lock ID to acquire -/// \param num_locks The number of locks to acquire -inline void _lock_acquire(int lock_id, int num_locks = 1){ - acquire_greater_equal(lock_id + 48, num_locks); -} - -/// \brief Release a lock with given lock ID on this CT and number of locks -/// \param lock_id The lock ID to release -/// \param num_locks The number of locks to release -inline void _lock_release(int lock_id, int num_locks = 1){ - release(lock_id + 48, num_locks); -} - - -/// \brief Acquire a lock with given lock ID on left CT and number of locks -/// \param lock_id The lock ID to acquire -/// \param num_locks The number of locks to acquire -inline void _left_lock_acquire(int lock_id, int num_locks = 1){ - acquire_greater_equal(lock_id + 16, num_locks); -} - -/// \brief Release a lock with given lock ID on left CT and number of locks -/// \param lock_id The lock ID to release -/// \param num_locks The number of locks to release -inline void _left_lock_release(int lock_id, int num_locks = 1){ - release(lock_id + 16, num_locks); -} - -/// \brief Acquire a lock with given lock ID on up CT and number of locks -/// \param lock_id The lock ID to acquire -/// \param num_locks The number of locks to acquire -inline void _up_lock_acquire(int lock_id, int num_locks = 1){ - acquire_greater_equal(lock_id + 32, num_locks); -} - -/// \brief Release a lock with given lock ID on up CT and number of locks -/// \param lock_id The lock ID to release -/// \param num_locks The number of locks to release -inline void _up_lock_release(int lock_id, int num_locks = 1){ - release(lock_id + 32, num_locks); -} - -/// \brief Acquire a lock with given lock ID on down CT and number of locks -/// \param lock_id The lock ID to acquire -/// \param num_locks The number of locks to acquire -inline void _down_lock_acquire(int lock_id, int num_locks = 1){ - acquire_greater_equal(lock_id, num_locks); -} - -/// \brief Release a lock with given lock ID on down CT and number of locks -/// \param lock_id The lock ID to release -/// \param num_locks The number of locks to release -inline void _down_lock_release(int lock_id, int num_locks = 1){ - release(lock_id, num_locks); -} - -template -void zero_vectorized(T *__restrict c) { - constexpr int r = 256 / (sizeof(T) * 8); // one 256 bit store unit - static_assert((M) % r == 0); - const aie::vector zeros = aie::zeros(); - const T *__restrict c_end = c + M; - for (; c < c_end; c += r) { - aie::store_v(c, zeros); - } -} - -template -void _memcpy(uint8* dst, uint8* src){ - static constexpr int vec_size = 256; - for (int i = 0; i < SIZE; i += vec_size){ - aie::vector data = aie::load_v(src + i); - aie::store_v(dst + i, data); - } -} - -// Ping/pong buffer selectors. Peano's loader does not zero .bss, so under Peano -// they live in .data. They are volatile there too: Peano does not treat a lock -// acquire as a memory barrier, so if it can prove two picks give the same buffer -// it reuses the earlier load, even though the DMA has refilled the buffer in between. -#if defined(__chess__) -#define AIE_PING_FLAG bool -#else -#define AIE_PING_FLAG __attribute__((section(".data"))) volatile bool -#endif - -// bf16 8x8x8 mmul with the BFP16 emulation, for Peano. It issues the same -// intrinsic as aie_api's emulated mac but converts B with the accumulator -// constructor rather than a multiply by one, which would take a multiplier slot -// from the macs. The conversion is exact, so results are unchanged. -#if !defined(__chess__) && defined(AIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16) -#include -struct aie_mmul_bf16_888 { - aie::accum acc; - explicit aie_mmul_bf16_888(const aie::vector &c) { acc.from_vector(c); } - __attribute__((always_inline)) void mac(const aie::vector &a, const aie::vector &b) { - aie::accum acc_a(a); - aie::accum acc_b(aie::transpose(b, 8, 8)); - acc = ::mac_8x8_8x8T_conf(::to_v64bfp16ebs8(acc_a), ::to_v64bfp16ebs8(acc_b), acc, 0, 0, 0); - } - template aie::vector to_vector() const { return acc.template to_vector(); } -}; -#endif - -#endif diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/common.hpp b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/common.hpp deleted file mode 100644 index b7ee38b08..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/common.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. - -///@file typedef.hpp -///@brief Define the typedefs for the kernels -#ifndef __COMMON_HPP__ -#define __COMMON_HPP__ - -#include -#include - -typedef bfloat16 bf16; - -constexpr int QXNX_ROW_BLOCK_SIZE = 32; -constexpr int QXNX_COL_BLOCK_SIZE = 256; -constexpr int GGML_GROUP_SIZE = 32; - -// A packed q4_k column holds the block's whole row span, so the quants are -// column major with PARALLEL_ROWS nibbles per column. -constexpr int PARALLEL_ROWS = QXNX_ROW_BLOCK_SIZE; - -constexpr bfloat16 exp_scale = 1.44269504089; -constexpr int NPU_M_TILE = 128; -constexpr int NPU_K_TILE = 256; // one k slice per K step: Din only needs to be a multiple of 256 -constexpr int NPU_N_TILE = 64; -constexpr int m_slice = 16; -constexpr int k_slice = QXNX_COL_BLOCK_SIZE; -constexpr int n_slice = QXNX_ROW_BLOCK_SIZE; -constexpr int y_slice = 256; -constexpr int y_num = NPU_M_TILE * NPU_N_TILE / y_slice; - -#endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/decode_core.cc b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/decode_core.cc deleted file mode 100644 index 04facd34e..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/decode_core.cc +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -// Portions of this file consist of AI-generated content. -// -// Stream core of the Inkling-2-Mini decode overlay. Everything arrives as a sequence of 4736-byte units (one Q4_K -// block each) on S2MM 1; a task starts with a header unit (int32 words, then the task's x at byte X_OFF), and its -// results leave as 96-float y units on MM2S 0. The core runs task after task and never returns. -// -// Tasks: -// OP_SINK [1] n: take n more units, emit one y unit (y[0] = n, y[1] = a byte sum) -// OP_GEMV_Q4K [1] groups, [2] col blocks nc, x = nc * 256 bf16: y = W x for groups of 96 rows, the weights in the -// NPU's block-triple order ([group][cb][3 row blocks], each block in q4k_to_npu order); one y unit -// per group, row 32 b + i of the group at y[32 b + i]. fp32 accumulation of bf16 weights x bf16 x. - -#include "aie_kernel_utils.h" -#include "common.hpp" - -static constexpr int UNIT = 4736; -static constexpr int RING = 4; -static constexpr int X_OFF = 128; -static constexpr int OP_SINK = 1, OP_GEMV_Q4K = 2; -static constexpr int W_PROD = 0, W_CONS = 1, Y_PROD = 2, Y_CONS = 3; -static constexpr uint8 Q4_BIASED_EXP_BYTE = 0x43; // 0x43 << 8 | q is the bf16 128 + q -static constexpr int NIBBLE_BIAS = 128; - -static inline __attribute__((always_inline)) aie::vector q4_biased(aie::vector nib, aie::vector hi) { - return aie::vector_cast(aie::concat(aie::interleave_zip(nib, hi, 1))); -} - -// lane r * 8 + k = v[r] -static inline __attribute__((always_inline)) aie::vector splat8(aie::vector v) { - aie::vector v16 = aie::concat(v, v); - aie::vector v32 = aie::concat(v16, v16); - return aie::transpose(aie::concat(v32, v32), 8, 8); -} - -// lane r * 8 + k = v[k] -static inline __attribute__((always_inline)) aie::vector rep8(aie::vector v) { - aie::vector v16 = aie::concat(v, v); - aie::vector v32 = aie::concat(v16, v16); - return aie::concat(v32, v32); -} - -// lane r * 8 + k = v[k], fp32 -static inline __attribute__((always_inline)) aie::vector rep8f(aie::vector v) { - aie::vector v16 = aie::concat(v, v); - aie::vector v32 = aie::concat(v16, v16); - return aie::concat(v32, v32); -} - -// The column block's x laid out for gemv_block: xr[kt] = rep8(x[8 kt .. 8 kt + 8]) (32 x 64 bf16) and -// xnr[g] = rep8 of the 8 values -128 sum_{kt of group g} x[8 kt + k] (8 x 64 fp32); xs[g] = the group's x sum. -static void prep_x(bf16* __restrict xr, float* __restrict xnr, bf16* __restrict xs, const bf16* __restrict xc) { - for (int kt = 0; kt < 32; kt++) aie::store_v(xr + 64 * kt, rep8(aie::load_v<8>(xc + 8 * kt))); - const bfloat16 nb = bfloat16(-NIBBLE_BIAS), one = bfloat16(1.0f); - aie::vector tot = aie::zeros(); - for (int g = 0; g < 8; g++) { - const bf16* xg = xr + 256 * g; - aie::accum t = aie::mul(aie::load_v<64>(xg), nb); - t = aie::mac(t, aie::load_v<64>(xg + 64), nb); - t = aie::mac(t, aie::load_v<64>(xg + 128), nb); - t = aie::mac(t, aie::load_v<64>(xg + 192), nb); - aie::store_v(xnr + 64 * g, t.to_vector()); - aie::accum u = aie::mul(aie::load_v<16>(xg), one); - u = aie::mac(u, aie::load_v<16>(xg + 64), one); - u = aie::mac(u, aie::load_v<16>(xg + 128), one); - u = aie::mac(u, aie::load_v<16>(xg + 192), one); - tot[g] = aie::reduce_add(u.to_vector().extract<8>(0)); - } - aie::accum ta; - ta.from_vector(tot); - aie::store_v(xs, rep8(ta.to_vector().extract<8>(0))); // lane r * 8 + g = the group sum -} - -// One Q4_K block (q4k_to_npu order) times the 256 x of its column block, into acc[hp][r 8][k 8] (hp = 2 H + par, -// row 16 H + 2 r + par of the block), fp32. Per 32-column group g the nibbles are used as the exact bf16 128 + q: -// p = sum (128 + q) x over the group, started at -128 sum x (xnr, fp32) so p = sum q x, then acc += bf16(p) * S sc. -// The min term M mn sum x goes in once per block from the group sums xs (lane r * 8 + g; the final reduce adds -// over the 8 lanes of a row whatever their meaning). ss: scratch for the scale splats (16 x 64 bf16). -static inline void gemv_block(float* __restrict acc, const uint8* __restrict blk, const float* __restrict xnr, - const bf16* __restrict xs, const bf16* __restrict xr, bf16* __restrict ss) { - const aie::vector hi = aie::broadcast(Q4_BIASED_EXP_BYTE); - const aie::vector xs8 = aie::load_v<64>(xs); - for (int hp = 0; hp < 4; hp++) { - const int H = hp >> 1, par = hp & 1; - const uint8* q = blk + 512 + 2048 * H + 1024 * par; - aie::accum t; - t.from_vector(aie::to_float(aie::load_v<64>(blk + 64 * hp), 0)); - const aie::vector a_sc = aie::mul(t.to_vector(), rep8(aie::load_v<8>((const bf16*)(blk + 4608) + 8 * hp))).to_vector(); - for (int g = 0; g < 8; g++) aie::store_v(ss + 64 * g, splat8(aie::shuffle_down(a_sc, 8 * g).extract<8>(0))); - aie::accum c(aie::load_v<64>(acc + 64 * hp)); - // min term: lanes r * 8 + g - t.from_vector(aie::to_float(aie::load_v<64>(blk + 256 + 64 * hp), 0)); - c = aie::mac(c, aie::transpose(aie::mul(t.to_vector(), rep8(aie::load_v<8>((const bf16*)(blk + 4672) + 8 * hp))).to_vector(), 8, 8), xs8); - AIE_LOOP_RANGE(8, 8) - for (int g = 0; g < 8; g++) { - aie::accum p(aie::load_v<64>(xnr + 64 * g)); - const bf16* xg = xr + 256 * g; - const uint8* qg = q + 128 * g; -#pragma clang loop unroll(full) - for (int j = 0; j < 4; j += 2) { - aie::vector u = aie::unpack(aie::vector_cast(aie::load_v<64>(qg + 32 * j))); - p = aie::mac(p, q4_biased(u.extract<64>(0), hi), aie::load_v<64>(xg + 64 * j)); - p = aie::mac(p, q4_biased(u.extract<64>(1), hi), aie::load_v<64>(xg + 64 * j + 64)); - } - c = aie::mac(c, p.to_vector(), aie::load_v<64>(ss + 64 * g)); - } - aie::store_v(acc + 64 * hp, c.to_vector()); - } -} - -extern "C" void decode_core(uint8* w0, uint8* w1, uint8* w2, uint8* w3, float* y0, float* y1, bf16* x, float* acc, - float* xnr, bf16* xs, bf16* xr, bf16* ss) { - aie::set_rounding(aie::rounding_mode::conv_even); - uint8* const W[RING] = {w0, w1, w2, w3}; - float* const Y[2] = {y0, y1}; - int wi = 0, yi = 0; - auto take = [&]() -> const uint8* { _lock_acquire(W_CONS); return W[wi]; }; - auto give = [&]() { _lock_release(W_PROD); if (++wi == RING) wi = 0; }; - auto y_get = [&]() -> float* { _lock_acquire(Y_PROD); return Y[yi]; }; - auto y_put = [&]() { _lock_release(Y_CONS); yi ^= 1; }; - - for (;;) { - const volatile int* h = (const volatile int*)take(); - const int op = h[0], a1 = h[1], a2 = h[2]; - if (op == OP_GEMV_Q4K) { - // x: nc * 512 bytes from X_OFF on, continuing into the following units - int left = a2 * 512, off = X_OFF; - uint8* xd = (uint8*)x; - const uint8* u = (const uint8*)h; - for (;;) { - const int n = left < UNIT - off ? left : UNIT - off; - for (int i = 0; i < n; i += 32) aie::store_v(xd + i, aie::load_v<32>(u + off + i)); - xd += n; left -= n; - give(); - if (left == 0) break; - u = take(); off = 0; - } - for (int g = 0; g < a1; g++) { - for (int i = 0; i < 12 * 64; i += 64) aie::store_v(acc + i, aie::zeros()); - for (int cb = 0; cb < a2; cb++) { - prep_x(xr, xnr, xs, x + 256 * cb); - for (int b = 0; b < 3; b++) { - gemv_block(acc + 256 * b, take(), xnr, xs, xr, ss); - give(); - } - } - float* y = y_get(); - for (int s = 0; s < 12; s++) { // s = 4 b + 2 H + par - const int b = s / 4, H = (s / 2) % 2, par = s % 2; - for (int r = 0; r < 8; r++) - y[32 * b + 16 * H + 2 * r + par] = aie::reduce_add(aie::load_v<8>(acc + 64 * s + 8 * r)); - } - y_put(); - } - } else { // OP_SINK - const int n = a1; - give(); - unsigned sum = 0; - for (int i = 0; i < n; i++) { - const uint8* u = take(); - sum += u[0]; - give(); - } - float* y = y_get(); - y[0] = (float)n; - y[1] = (float)sum; - y_put(); - } - } -} diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/hub.cc b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/hub.cc deleted file mode 100644 index 5f74e1961..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/hub.cc +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -// Portions of this file consist of AI-generated content. -// -// Hub core of the Inkling-2-Mini decode overlay: drives the 16 weight streams itself. Per call it waits for the -// host's start lock, reads the weight buffer's address from shim 0 BD BASE_BD (once), then points BD SHIM_BD + ch -// of every shim at the stream it chooses and pushes it. -// -// Probe call (args): [0] bytes per channel task, [1] channel stride in bytes, [2] extra offset in bytes, [3] debug: 1 push only, 2 read + push, [4] trace on, [5] channels, [6] rounds (timing), [7] absolute base in [8] lo, [9] hi. - -#include "hub_ctrl.hpp" - -static constexpr int START = 10, TR_PROD = 11, TR_CONS = 12; -static constexpr uint32_t SHIM_BD = 4, BASE_BD = 15; // BASE_BD of shim 0: the host points it at the buffer (never started) -// control packet ids to shim j and of the read responses: must match CTRL_IDS / RESP_ID in iron/decode_aie.py -static constexpr uint32_t CTRL_ID[8] = {5, 8, 17, 31, 22, 30, 21, 23}, RESP_ID = 9; - -// debug progress words on MM2S 0 (args[4] != 0, the 8-channel debug build only) -static void trace(volatile uint32_t* tr, const int32_t* args, uint32_t v) { - if (!args[4]) return; - _lock_acquire(TR_PROD); - tr[0] = v; - _lock_release(TR_CONS); -} - -static volatile uint32_t* g_tr; -static void tp(uint32_t v) { _lock_acquire(TR_PROD); g_tr[0] = v; _lock_release(TR_CONS); } - -extern "C" void hub(uint32_t* out, uint32_t* in, int32_t* args, uint32_t* tr) { - _lock_acquire(START); - trace(tr, args, 1); - static uint32_t base_lo, base_hi; - static bool known = false; - const int dbg = args[3]; - g_tr = tr; - if (args[7]) { // probe: the base is a device address the host passes (any BO, not a run argument) - base_lo = (uint32_t)args[8]; - base_hi = (uint32_t)args[9]; - } else if (!known && dbg != 1) { - base_lo = hub_ctrl::shim_read(out, in, CTRL_ID[0], RESP_ID, hub_ctrl::bd_addr(BASE_BD) + 4, args[4] ? tp : nullptr); - trace(tr, args, 2); - base_hi = hub_ctrl::shim_read(out, in, CTRL_ID[0], RESP_ID, hub_ctrl::bd_addr(BASE_BD) + 8); - known = true; - trace(tr, args, 3); - trace(tr, args, base_lo); - trace(tr, args, base_hi); - } - const uint32_t bytes = (uint32_t)args[0], stride = (uint32_t)args[1], extra = (uint32_t)args[2]; - const uint32_t C = (uint32_t)args[5], R = args[6] > 0 ? (uint32_t)args[6] : 1; - for (uint32_t r = 0; r < R; r++) - for (uint32_t c = 0; c < C; c++) { - const uint32_t col = c % 8, ch = c / 8; - trace(tr, args, 0x100 + c); - if (dbg == 0) hub_ctrl::shim_bd(out, CTRL_ID[col], SHIM_BD + ch, base_lo, base_hi, c * stride + extra, bytes / 4); - if (c == 0) trace(tr, args, 4); - hub_ctrl::shim_push(out, CTRL_ID[col], ch, SHIM_BD + ch); - } - trace(tr, args, 0xD0E); -} diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/hub_ctrl.hpp b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/hub_ctrl.hpp deleted file mode 100644 index ba8df0bbe..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/kernel/hub_ctrl.hpp +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -// Portions of this file consist of AI-generated content. -// -// Control packets from a core to the shim tiles: read a shim BD's address words once, then point shim BDs at -// device-chosen offsets of the same buffer and push them on the shim's MM2S task queues. The core sends the -// packets through its own MM2S channel CTRL_PORT (BD CTRL_OUT_BD, buffer `out`, locks OUT_PROD / OUT_CONS) and -// takes the read responses on S2MM CTRL_PORT (one word into `in`, locks IN_PROD / IN_CONS). Needs the core's -// processor bus (host: maskwrite 0x32038 bit 0) to resize its own BD. - -#pragma once -#include - -#include "aie_kernel_utils.h" - -namespace hub_ctrl { - -constexpr uint32_t CTRL_PORT = 1, CTRL_OUT_BD = 10; -constexpr int OUT_PROD = 6, OUT_CONS = 7, IN_PROD = 8, IN_CONS = 9; - -constexpr uint32_t bd_addr(uint32_t bd) { return 0x1D000u + bd * 0x20u; } -constexpr uint32_t SHIM_MM2S_QUEUE[2] = {0x1D214u, 0x1D21Cu}; - -inline uint32_t parity_bit(uint32_t v) { return (uint32_t)(__builtin_popcount(v) & 1) ^ 1u; } // makes the count odd - -// control word: response packet id, op 0 write / 1 read, beats = data words - 1, register address -inline uint32_t ctrl_word(uint32_t resp_id, uint32_t op, uint32_t beats, uint32_t addr) { - const uint32_t w = resp_id << 24 | op << 22 | beats << 20 | addr; - return w | parity_bit(w) << 31; -} - -// packet header from this core (type 0) -inline uint32_t pkt_header(uint32_t id) { - const uint32_t h = (uint32_t)get_coreid() << 16 | id; - return h | parity_bit(h) << 31; -} - -inline void bus_write(uint32_t v, uint32_t addr) { write_tm(v, addr); } -inline uint32_t bus_read(uint32_t addr) { return read_tm(addr); } - -inline void sched_barrier() { - __builtin_aie2p_sched_barrier(); - volatile int32_t k = 0; - k++; - __builtin_aie2p_sched_barrier(); -} - -// resize this core's control BD to `words` and start it once -inline void send_len(uint32_t words) { - const uint32_t ctrl = CTRL_PORT == 0 ? 0x1DE10u : 0x1DE18u, queue = CTRL_PORT == 0 ? 0x1DE14u : 0x1DE1Cu; - const uint32_t w0 = bus_read(bd_addr(CTRL_OUT_BD)); - sched_barrier(); - bus_write((w0 & ~0x3FFFu) | words, bd_addr(CTRL_OUT_BD)); - sched_barrier(); - bus_write(1u << 1, ctrl); - sched_barrier(); - bus_write(1u, ctrl); // as hy-mem - sched_barrier(); - bus_write(CTRL_OUT_BD, queue); - sched_barrier(); -} - -// one register of a shim tile (packet id `id`, responses on `resp_id`) -inline uint32_t shim_read(uint32_t* out, volatile uint32_t* in, uint32_t id, uint32_t resp_id, uint32_t addr, void (*tp)(uint32_t) = nullptr) { - send_len(2); - if (tp) tp(0x11); - _lock_acquire(OUT_PROD); - out[0] = pkt_header(id); - out[1] = ctrl_word(resp_id, 1, 0, addr); - _lock_release(OUT_CONS); - if (tp) tp(0x12); - _lock_acquire(IN_CONS); - const uint32_t v = in[0]; - _lock_release(IN_PROD); - return v; -} - -// shim BD `bd`: words 0-2 = length (32-bit words), address base + offset (48 bits, carry into word 2) -inline void shim_bd(uint32_t* out, uint32_t id, uint32_t bd, uint32_t base_lo, uint32_t base_hi, uint32_t offset, uint32_t words) { - const uint32_t lo = base_lo + offset; - const uint32_t hi = (base_hi & 0xFFFF0000u) | (((base_hi & 0xFFFFu) + (lo < base_lo)) & 0xFFFFu); - send_len(5); - _lock_acquire(OUT_PROD); - out[0] = pkt_header(id); - out[1] = ctrl_word(0, 0, 2, bd_addr(bd)); - out[2] = words; - out[3] = lo; - out[4] = hi; - _lock_release(OUT_CONS); -} - -// push shim BD `bd` on MM2S channel `ch`'s task queue -inline void shim_push(uint32_t* out, uint32_t id, uint32_t ch, uint32_t bd) { - send_len(3); - _lock_acquire(OUT_PROD); - out[0] = pkt_header(id); - out[1] = ctrl_word(0, 0, 0, SHIM_MM2S_QUEUE[ch]); - out[2] = bd; - _lock_release(OUT_CONS); -} - -} // namespace hub_ctrl diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/bitstream.mk b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/bitstream.mk deleted file mode 100644 index 2d7c025e2..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/bitstream.mk +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -# Portions of this file consist of AI-generated content. - -MLIR_O_DIR := build/mlir -BITSTREAM_O_DIR := build/bitstream - -IRON_SRC := $(wildcard ${HOME_DIR}/iron/*_aie.py) -IRON_OTHER_SRC := $(wildcard ${HOME_DIR}/iron/*.py) -IRON_MLIR_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${MLIR_O_DIR}/%.mlir, ${IRON_SRC}) -IRON_XCLBIN_TARGET := $(patsubst ${HOME_DIR}/iron/%_aie.py, ${BITSTREAM_O_DIR}/from_iron/%.xclbin, ${IRON_SRC}) - -.PRECIOUS: ${IRON_MLIR_TARGET} - -AIECC_FLAGS := --aie-generate-cdo --no-compile-host --no-xchesscc --no-xbridge --alloc-scheme=basic-sequential - -${MLIR_O_DIR}/%.mlir: ${HOME_DIR}/iron/%_aie.py ${IRON_OTHER_SRC} - mkdir -p ${@D} - python3 $< > $@ - -${BITSTREAM_O_DIR}/from_iron/%.xclbin: ${MLIR_O_DIR}/%.mlir ${KERNEL_OBJS} - mkdir -p ${@D} - cp ${KERNEL_OBJS} ${@D} - cd ${@D} && aiecc.py ${AIECC_FLAGS} --aie-generate-xclbin \ - --xclbin-name=${@F} $(<:${MLIR_O_DIR}/%=../../mlir/%) - python3 ${HOME_DIR}/check_routes.py ${@D}/$(*F).mlir.prj/input_physical.mlir $< - mkdir -p build/xclbins - cp ${@} build/xclbins/ - -XCLBIN_TARGETS += ${IRON_XCLBIN_TARGET} diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/common.mk b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/common.mk deleted file mode 100755 index 2d66b1266..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/common.mk +++ /dev/null @@ -1,31 +0,0 @@ -# common.mk -# This file is licensed under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -# Copyright (C) 2024, Advanced Micro Devices, Inc. -# Created by Alfred - -ifneq ($(filter -j,$(MAKEFLAGS)),) - # Nothing to do; -j is already set -else - MAKEFLAGS += -j8 -endif - -# VITIS related variables (Chess only: ENABLE_CHESSCC=1; Peano builds never expand them) -AIETOOLS_DIR ?= $(or $(AIETOOLS_ROOT),$(patsubst %/bin/,%,$(dir $(shell command -v xchesscc 2>/dev/null)))) -# Expanded only inside the Chess recipes, so it fires only for ENABLE_CHESSCC=1. -AIETOOLS_CHECK = $(if $(strip $(AIETOOLS_DIR)),,$(error ENABLE_CHESSCC=1 needs Vitis AIE Essentials: set AIETOOLS_ROOT (or AIETOOLS_DIR), or put xchesscc on PATH)) -AIE_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/versal_prod/lib -AIE2_INCLUDE_DIR ?= ${AIETOOLS_DIR}/data/aie_ml/lib - -AIEOPT_DIR ?= $(shell realpath $(dir $(shell which aie-opt))/..) - -WARNING_FLAGS = -Wno-parentheses -Wno-attributes -Wno-macro-redefined - - -CHESSCCWRAP1_FLAGS = aie $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include -CHESSCCWRAP2_FLAGS = aie2 $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include -CHESSCCWRAP2P_FLAGS = aie2p $(AIETOOLS_CHECK)-I ${AIETOOLS_DIR}/include -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 -PEANOWRAP2_FLAGS = -O2 -v -std=c++20 --target=aie2-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -I ${AIEOPT_DIR}/include -PEANOWRAP2P_FLAGS = -O2 -v -std=c++20 --target=aie2p-none-unknown-elf ${WARNING_FLAGS} -DNDEBUG -DAIE_API_EMULATE_BFLOAT16_MMUL_WITH_BFP16 -I ${AIEOPT_DIR}/include diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/host.mk b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/host.mk deleted file mode 100644 index 614821427..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/host.mk +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved. -# Portions of this file consist of AI-generated content. - -HOST_C_TARGET := run.exe -HOST_COMMON_DIR := ../../host_common -CXX := g++-13 -CXX_FLAGS := -std=c++20 -fPIC -Wall -O2 -march=native -fopenmp -CXX_FLAGS += -Ihost -I$(HOST_COMMON_DIR) -I/opt/xilinx/xrt/include -MMD -MP - -LDFLAGS += -L/opt/xilinx/xrt/lib -LDFLAGS += -lxrt_coreutil $(HOST_COMMON_DIR)/../../../src/lib/xrt/libaiebu.a -LDFLAGS += -lboost_program_options -lboost_filesystem -fopenmp - -HOST_SOURCES := $(shell find host -name '*.cpp') -HOST_OBJECTS := $(HOST_SOURCES:%.cpp=build/%.o) -HOST_DEPENDS := $(HOST_OBJECTS:.o=.d) - -$(HOST_C_TARGET): build/$(HOST_C_TARGET) - cp build/$(HOST_C_TARGET) ./ - -build/$(HOST_C_TARGET): $(HOST_OBJECTS) - @mkdir -p $(dir $@) - $(CXX) $(CXX_FLAGS) $^ -o $@ $(LDFLAGS) - -build/%.o: %.cpp - @mkdir -p $(dir $@) - $(CXX) $(CXX_FLAGS) -c $< -o $@ - --include $(HOST_DEPENDS) diff --git a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/kernel.mk b/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/kernel.mk deleted file mode 100755 index 56317c4ef..000000000 --- a/flm-dev-kit/FLM_Xclbin/Inkling2/decode/makefiles/kernel.mk +++ /dev/null @@ -1,25 +0,0 @@ -# common.mk -# This file is licensed under the Apache License v2.0 with LLVM Exceptions. -# See https://llvm.org/LICENSE.txt for license information. -# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -# -# Copyright (C) 2024, Advanced Micro Devices, Inc. -# Portions of this file consist of AI-generated content. -# Created by Alfred - -# Kernel stuff -KERNEL_O_DIR := build/$(MODEL_TYPE)/kernel -KERNEL_SRCS := $(wildcard ${HOME_DIR}/kernel/*.cc) -KERNEL_OBJS := $(patsubst ${HOME_DIR}/kernel/%.cc, ${KERNEL_O_DIR}/%.o, $(KERNEL_SRCS)) -KERNEL_HEADERS := $(wildcard ${HOME_DIR}/kernel/*.h ${HOME_DIR}/kernel/*.hpp) - -# Build kernels -ENABLE_CHESSCC ?= 0 - -${KERNEL_O_DIR}/%.o: ${HOME_DIR}/kernel/%.cc ${KERNEL_HEADERS} - mkdir -p ${@D} -ifeq ($(ENABLE_CHESSCC),1) - cd ${@D} && xchesscc_wrapper ${CHESSCCWRAP2P_FLAGS} -DNPU2 ${KERNEL_ARGS} ${EXTRA_KARGS} -c $< -o ${@F} -else - cd ${@D} && ${PEANO_INSTALL_DIR}/bin/clang++ ${PEANOWRAP2P_FLAGS} -DNPU2 ${KERNEL_ARGS} ${EXTRA_KARGS} -c $< -o ${@F} -endif \ No newline at end of file diff --git a/flm-dev-kit/FLM_Xclbin/build_units.json b/flm-dev-kit/FLM_Xclbin/build_units.json index 3522f374b..73de67b21 100644 --- a/flm-dev-kit/FLM_Xclbin/build_units.json +++ b/flm-dev-kit/FLM_Xclbin/build_units.json @@ -341,12 +341,6 @@ "xclbins-Hy_mem_30BA3B_prefill_overlay" ] }, - "Inkling2/decode": { - "model_types": [], - "artifacts": [ - "xclbins-Inkling2_decode" - ] - }, "Inkling2/decode_layer": { "model_types": [], "artifacts": [