MLIR-AIE 1.4.6.dev
parameter_scratchpad.h
Go to the documentation of this file.
1//===- parameter_scratchpad.h - Host-side parameter runtime ------*- C++-*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// ParameterScratchpad: Host-side runtime class for writing named parameters
9// to AIE cores via the scratchpad mechanism.
10//
11// Usage:
12// auto params = test_utils::ParameterScratchpad(run, "params.txt");
13// params.write("foo", 42u);
14// params.write("bar", std::bfloat16_t(3.14f));
15// params.sync();
16//
17// A module of several commands, runtime sequences no `aiex.run` calls, gives
18// each its own scratchpad, in which parameters of different commands may
19// share a slot: construct each command's with its `device:sequence` name, and
20// write it with that command's parameters (`names()`) only. With no name, the
21// module must have one command.
22//
23//===----------------------------------------------------------------------===//
24
25#ifndef AIE_RUNTIME_TEST_LIB_PARAMETER_SCRATCHPAD_H
26#define AIE_RUNTIME_TEST_LIB_PARAMETER_SCRATCHPAD_H
27
28#include <cstdint>
29#include <cstring>
30#include <fstream>
31#include <stdexcept>
32#include <string>
33#include <unordered_map>
34#include <unordered_set>
35#include <utility>
36#include <vector>
37
38#if !defined(TEST_UTILS_USE_XRT)
39#if defined(__has_include) && __has_include(<xrt/xrt_bo.h>) && \
40 __has_include(<xrt/xrt_kernel.h>)
41#define TEST_UTILS_USE_XRT 1
42#else
43#define TEST_UTILS_USE_XRT 0
44#endif
45#endif
46
47#if TEST_UTILS_USE_XRT
48#include <xrt/xrt_bo.h>
49#include <xrt/xrt_kernel.h>
50#endif
51
52namespace test_utils {
53
55public:
56#if TEST_UTILS_USE_XRT
57 /// Construct from an XRT run handle (C++ usage), for the parameters of
58 /// `command` (`device:sequence`), or of the module's one command when it
59 /// is empty.
60 ParameterScratchpad(xrt::run &run, const std::string &paramsPath,
61 const std::string &command = "") {
62 parseParams(paramsPath);
63 selectCommand(command, paramsPath);
64 scratchpadBo = run.get_ctrl_scratchpad_bo();
65 boMap = scratchpadBo.map<uint32_t *>();
66 if (scratchpadBo.size() < scratchpadSizeBytes)
67 throw std::runtime_error("ParameterScratchpad: BO size (" +
68 std::to_string(scratchpadBo.size()) +
69 ") < required scratchpad size (" +
70 std::to_string(scratchpadSizeBytes) + ")");
71 clear();
72 }
73#endif
74
75 /// Construct from a raw buffer and its size in bytes (Python bindings /
76 /// testing). The size is required: clear() and every write index off
77 /// scratchpadSizeBytes, which parseParams derives from the params file, not
78 /// from the buffer.
79 ParameterScratchpad(uint32_t *buffer, size_t bufferSizeBytes,
80 const std::string &paramsPath,
81 const std::string &command = "")
82 : boMap(buffer) {
83 parseParams(paramsPath);
84 selectCommand(command, paramsPath);
85 if (bufferSizeBytes < scratchpadSizeBytes)
86 throw std::runtime_error("ParameterScratchpad: buffer size (" +
87 std::to_string(bufferSizeBytes) +
88 ") < required scratchpad size (" +
89 std::to_string(scratchpadSizeBytes) + ")");
90 clear();
91 }
92
93 /// Write raw bytes (up to 4) by name, interpreted as a little-endian
94 /// uint32. For core-kind parameters, the bits are left-shifted by 2
95 /// (firmware requirement); for repeat-kind ones, by 16 (into the task
96 /// queue's repeat field).
97 /// For addr-kind parameters, the value is written raw (no shift).
98 void writeBytes(const std::string &name, const void *data, size_t len) {
99 uint32_t bits = 0;
100 std::memcpy(&bits, data, std::min(len, sizeof(bits)));
101 writeBits(name, bits);
102 }
103
104 /// Write a raw 32-bit value by name. For core-kind parameters, the bits
105 /// are left-shifted by 2 (firmware requirement); for repeat-kind ones, by
106 /// 16 (into the task queue's repeat field). For addr-kind parameters,
107 /// the value is written directly (no shift). A DMA offset or length
108 /// parameter's value, read as an int32, must lie in the range the compiler
109 /// gave it, which keeps its transfers within their buffers; a repeat
110 /// parameter's, at most its task's repeat count. An offset into elements
111 /// narrower than 4 bytes must be a multiple of the elements in a word, or
112 /// the DMA would round its address down.
113 void writeBits(const std::string &name, uint32_t bits) {
114 unsigned index = memberSlot(name);
115 if (auto multiple = offsetMultiples.find(name);
116 multiple != offsetMultiples.end() &&
117 static_cast<int32_t>(bits) % multiple->second)
118 throw std::invalid_argument(
119 "ParameterScratchpad: value " +
120 std::to_string(static_cast<int32_t>(bits)) + " of '" + name +
121 "' is not a multiple of " + std::to_string(multiple->second) +
122 " elements, which the DMA address it offsets needs to stay "
123 "4-byte aligned");
124 if (auto range = ranges.find(name); range != ranges.end()) {
125 int32_t value = static_cast<int32_t>(bits);
126 if (value < range->second.first || value > range->second.second)
127 throw std::invalid_argument(
128 "ParameterScratchpad: value " + std::to_string(value) + " of '" +
129 name + "' is outside [" + std::to_string(range->second.first) +
130 ", " + std::to_string(range->second.second) + "], " +
131 (kinds.at(name) == "repeat"
132 ? "its task's largest repeat count"
133 : "which keeps its DMA transfers within their buffers"));
134 values[name] = value;
135 }
136 boMap[index] = bits << kindShift(kinds.at(name));
137 }
138
139 /// Write a typed parameter value. For core-kind parameters, the raw bits
140 /// are left-shifted by 2 as required by the firmware's UPDATE_REG Incr mode,
141 /// and the core right-shifts (unsigned) by 2 after reading. The round trip
142 /// therefore zeroes the top 2 bits of the value (the bottom 2 bits are
143 /// preserved). Types that fit in 30 bits (e.g. uint16_t, int16_t,
144 /// std::bfloat16_t, and uint32_t values < 2^30) round-trip losslessly.
145 /// `float` is not supported as a core-kind parameter (the verifier in
146 /// `--aie-lower-scratchpad-parameters` rejects it).
147 template <typename T>
148 void write(const std::string &name, T value) {
149 static_assert(sizeof(T) <= 4, "Parameter values must be at most 32 bits");
150 uint32_t bits = 0;
151 std::memcpy(&bits, &value, sizeof(T));
152 writeBits(name, bits);
153 }
154
155 /// Check the written values of each offset and length parameter pair that
156 /// one DMA transfer uses. Throws std::invalid_argument if they take the
157 /// transfer past the end of its buffer.
158 void validate() const {
159 for (const JointBound &bound : jointBounds) {
160 int64_t offset = values.at(bound.offset);
161 int64_t length = values.at(bound.length);
162 int64_t end = offset + bound.lengthStep * length;
163 if (end > bound.max)
164 throw std::invalid_argument(
165 "ParameterScratchpad: '" + bound.offset +
166 "' = " + std::to_string(offset) + " plus " +
167 std::to_string(bound.lengthStep) + " * '" + bound.length +
168 "' = " + std::to_string(length) + " is " + std::to_string(end) +
169 ", above " + std::to_string(bound.max) +
170 ", so a DMA transfer using both runs past its buffer");
171 }
172 }
173
174#if TEST_UTILS_USE_XRT
175 /// Validate, then sync the scratchpad buffer to device. Call after all writes
176 /// for this run.
177 void sync() {
178 validate();
179 scratchpadBo.sync(XCL_BO_SYNC_BO_TO_DEVICE);
180 }
181#endif
182
183 /// The parameters this scratchpad holds: its command's.
184 std::vector<std::string> names() const {
185 return std::vector<std::string>(members.begin(), members.end());
186 }
187
188 /// Where firmware reads a parameter, for a runtime that stages the table
189 /// itself or fills a slot from elsewhere: the slot's index, the left shift
190 /// writeBits applies for its kind, the kind and the scalar type.
191 struct Slot {
192 unsigned index;
193 unsigned shift;
194 std::string kind;
195 std::string type;
196 };
197
198 Slot slot(const std::string &name) const {
199 unsigned index = memberSlot(name);
200 const std::string &kind = kinds.at(name);
201 return {index, kindShift(kind), kind, types.at(name)};
202 }
203
204 /// The number of 32-bit slots the scratchpad of `paramsPath` holds, for a
205 /// caller that allocates the buffer.
206 static unsigned slotCount(const std::string &paramsPath) {
207 std::ifstream file(paramsPath);
208 unsigned numParams = 0, numSlots = 0;
209 if (!(file >> numParams >> numSlots))
210 throw std::runtime_error(
211 "ParameterScratchpad: missing parameter and slot counts in '" +
212 paramsPath + "'");
213 return numSlots;
214 }
215
216 /// Read back a parameter's current encoded value (for debugging).
217 uint32_t read(const std::string &name) const {
218 return boMap[memberSlot(name)];
219 }
220
221private:
222#if TEST_UTILS_USE_XRT
223 xrt::bo scratchpadBo;
224#endif
225 uint32_t *boMap = nullptr;
226 size_t scratchpadSizeBytes = 0;
227 std::unordered_map<std::string, uint8_t> paramMap;
228 std::unordered_set<std::string> unslotted; // params no command reads
229 // Each parameter's kind ("core", "addr" or "repeat") and scalar type.
230 std::unordered_map<std::string, std::string> kinds, types;
231 std::unordered_map<std::string, std::pair<int32_t, int32_t>> ranges;
232 std::unordered_map<std::string, int32_t> values; // of the ranged params
233 // Offset parameters into elements narrower than a word, by the element
234 // count whose bytes fill one.
235 std::unordered_map<std::string, int32_t> offsetMultiples;
236 struct JointBound {
237 std::string length, offset;
238 int64_t lengthStep, max;
239 };
240 std::vector<JointBound> jointBounds;
241 // Each command's parameters, by `device:sequence`.
242 std::unordered_map<std::string, std::unordered_set<std::string>> commands;
243 std::vector<std::string> commandNames; // in params.txt order
244 std::string command;
245 std::unordered_set<std::string> members;
246
247 /// A core reads its slot shifted back down, as firmware's UPDATE_REG Incr
248 /// masks the low two bits; a repeat count sits in the task queue word's
249 /// repeat field; an address is added as it is.
250 static unsigned kindShift(const std::string &kind) {
251 return kind == "core" ? 2 : kind == "repeat" ? 16 : 0;
252 }
253
254 /// The slot of `name`, one of this command's parameters. Another command's
255 /// may share a slot with one of this command's, so it is refused too.
256 unsigned memberSlot(const std::string &name) const {
257 if (unslotted.count(name))
258 throw std::runtime_error("ParameterScratchpad: no command reads "
259 "parameter '" +
260 name + "', so it has no slot");
261 auto it = paramMap.find(name);
262 if (it == paramMap.end())
263 throw std::runtime_error("ParameterScratchpad: unknown parameter '" +
264 name + "'");
265 if (!members.count(name))
266 throw std::runtime_error("ParameterScratchpad: command '" + command +
267 "' does not read parameter '" + name +
268 "', whose slot another of its parameters may "
269 "hold");
270 return it->second;
271 }
272
273 void selectCommand(const std::string &name, const std::string &path) {
274 command = name;
275 if (name.empty()) {
276 if (commandNames.empty())
277 throw std::runtime_error("ParameterScratchpad: '" + path +
278 "' lists no command to hold parameters for");
279 if (commandNames.size() > 1) {
280 std::string available;
281 for (const std::string &entry : commandNames)
282 available += (available.empty() ? "" : ", ") + entry;
283 throw std::runtime_error(
284 "ParameterScratchpad: '" + path + "' lists " +
285 std::to_string(commandNames.size()) +
286 " commands, whose parameters may share slots: name the one this "
287 "scratchpad is for, of " +
288 available);
289 }
290 command = commandNames.front();
291 }
292 auto it = commands.find(command);
293 if (it == commands.end())
294 throw std::runtime_error("ParameterScratchpad: '" + path +
295 "' has no command '" + name + "'");
296 members = it->second;
297 }
298
299 void clear() {
300 for (size_t i = 0; i < scratchpadSizeBytes / 4; i++) {
301 boMap[i] = 0;
302 }
303 }
304
305 void parseParams(const std::string &path) {
306 std::ifstream file(path);
307 if (!file.is_open()) {
308 throw std::runtime_error("ParameterScratchpad: cannot open '" + path +
309 "'");
310 }
311
312 // Format (emitScratchpadParamsFile's):
313 // <num_parameters> <num_slots>
314 // <name> <state_table_idx> <type> <kind> <min> <max>
315 // ...
316 // <num_joint_bounds>
317 // <length> <offset> <length_step> <max>
318 // ...
319 // <num_commands>
320 // <device>:<sequence> <num_read> <name> ...
321 // ...
322 // <num_offset_multiples>
323 // <name> <multiple>
324 // ...
325 // where <state_table_idx> is "-" for a parameter no command reads, kind
326 // is "core", "addr" or "repeat", and <min> <max> is "- -" for a parameter
327 // with no range. A joint bound requires
328 // offset + length_step * length <= max. The offset multiples, absent when
329 // no offset needs one, list the offset parameters whose value must be a
330 // multiple.
331 unsigned numParams = 0, numSlots = 0;
332 file >> numParams >> numSlots;
333 if (!file)
334 throw std::runtime_error(
335 "ParameterScratchpad: missing parameter and slot counts in '" + path +
336 "'");
337 scratchpadSizeBytes = numSlots * 4;
338
339 for (unsigned i = 0; i < numParams; i++) {
340 std::string name, slot, type, kind, min, max;
341 file >> name >> slot >> type >> kind >> min >> max;
342 if (!file)
343 throw std::runtime_error("ParameterScratchpad: malformed entry " +
344 std::to_string(i) + " in '" + path + "'");
345 if (paramMap.count(name) || unslotted.count(name))
346 throw std::runtime_error(
347 "ParameterScratchpad: duplicate parameter name '" + name + "'");
348 if (slot == "-") {
349 unslotted.insert(name);
350 } else {
351 unsigned long idx = 0;
352 try {
353 idx = std::stoul(slot);
354 } catch (const std::logic_error &) {
355 throw std::runtime_error("ParameterScratchpad: malformed slot '" +
356 slot + "' for parameter '" + name +
357 "' in '" + path + "'");
358 }
359 if (idx >= numSlots)
360 throw std::runtime_error("ParameterScratchpad: state_table_idx " +
361 std::to_string(idx) + " for '" + name +
362 "' is past the " + std::to_string(numSlots) +
363 " slots of '" + path + "'");
364 paramMap[name] = static_cast<uint8_t>(idx);
365 }
366 if (kind != "core" && kind != "addr" && kind != "repeat")
367 throw std::runtime_error("ParameterScratchpad: invalid kind '" + kind +
368 "' for parameter '" + name + "'");
369 kinds[name] = kind;
370 types[name] = type;
371 if (min != "-") {
372 try {
373 ranges[name] = {std::stoi(min), std::stoi(max)};
374 } catch (const std::logic_error &) {
375 throw std::runtime_error("ParameterScratchpad: malformed range '" +
376 min + " " + max + "' for parameter '" +
377 name + "' in '" + path + "'");
378 }
379 values[name] = 0;
380 }
381 }
382
383 unsigned numJointBounds = 0;
384 file >> numJointBounds;
385 if (!file)
386 throw std::runtime_error(
387 "ParameterScratchpad: missing joint bound count in '" + path + "'");
388 for (unsigned i = 0; i < numJointBounds; i++) {
389 JointBound bound;
390 file >> bound.length >> bound.offset >> bound.lengthStep >> bound.max;
391 if (!file)
392 throw std::runtime_error("ParameterScratchpad: malformed joint bound " +
393 std::to_string(i) + " in '" + path + "'");
394 for (const std::string &name : {bound.length, bound.offset})
395 if (!ranges.count(name))
396 throw std::runtime_error("ParameterScratchpad: joint bound " +
397 std::to_string(i) + " names '" + name +
398 "', which has no range, in '" + path + "'");
399 jointBounds.push_back(bound);
400 }
401
402 unsigned numCommands = 0;
403 file >> numCommands;
404 if (!file)
405 throw std::runtime_error(
406 "ParameterScratchpad: missing command count in '" + path + "'");
407 for (unsigned i = 0; i < numCommands; i++) {
408 std::string name;
409 unsigned numRead = 0;
410 file >> name >> numRead;
411 commandNames.push_back(name);
412 std::unordered_set<std::string> &reads = commands[name];
413 for (unsigned j = 0; j < numRead; j++) {
414 std::string param;
415 file >> param;
416 if (file && !paramMap.count(param))
417 throw std::runtime_error("ParameterScratchpad: command '" + name +
418 "' names unknown parameter '" + param +
419 "' in '" + path + "'");
420 reads.insert(param);
421 }
422 if (!file)
423 throw std::runtime_error("ParameterScratchpad: malformed command " +
424 std::to_string(i) + " in '" + path + "'");
425 }
426
427 unsigned numMultiples = 0;
428 if (!(file >> numMultiples))
429 return;
430 for (unsigned i = 0; i < numMultiples; i++) {
431 std::string name;
432 int32_t multiple = 0;
433 file >> name >> multiple;
434 if (!file || multiple < 1)
435 throw std::runtime_error("ParameterScratchpad: malformed offset "
436 "multiple " +
437 std::to_string(i) + " in '" + path + "'");
438 if (!paramMap.count(name))
439 throw std::runtime_error("ParameterScratchpad: offset multiple " +
440 std::to_string(i) +
441 " names unknown "
442 "parameter '" +
443 name + "' in '" + path + "'");
444 offsetMultiples[name] = multiple;
445 }
446 }
447};
448
449} // namespace test_utils
450
451#endif // AIE_RUNTIME_TEST_LIB_PARAMETER_SCRATCHPAD_H
void writeBytes(const std::string &name, const void *data, size_t len)
Write raw bytes (up to 4) by name, interpreted as a little-endian uint32.
void writeBits(const std::string &name, uint32_t bits)
Write a raw 32-bit value by name.
void validate() const
Check the written values of each offset and length parameter pair that one DMA transfer uses.
static unsigned slotCount(const std::string &paramsPath)
The number of 32-bit slots the scratchpad of paramsPath holds, for a caller that allocates the buffer...
uint32_t read(const std::string &name) const
Read back a parameter's current encoded value (for debugging).
void write(const std::string &name, T value)
Write a typed parameter value.
Slot slot(const std::string &name) const
std::vector< std::string > names() const
The parameters this scratchpad holds: its command's.
ParameterScratchpad(uint32_t *buffer, size_t bufferSizeBytes, const std::string &paramsPath, const std::string &command="")
Construct from a raw buffer and its size in bytes (Python bindings / testing).
Where firmware reads a parameter, for a runtime that stages the table itself or fills a slot from els...