Loading...
Searching...
No Matches
AotiPackageIsa.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "AotiPackageIsa.h"
6
7#include <algorithm>
8#include <cctype>
9#include <cstdint>
10#include <filesystem>
11#include <fstream>
12#include <iostream>
13#include <iterator>
14#include <sstream>
15#include <stdexcept>
16#include <utility>
17
18#if defined(__x86_64__) || defined(__i386__)
19#include <cpuid.h>
20#endif
21
22namespace pot {
23namespace {
24
25constexpr std::uint32_t kEndOfCentralDirectory = 0x06054b50;
26constexpr std::uint32_t kZip64Locator = 0x07064b50;
27constexpr std::uint32_t kZip64EndOfCentralDirectory = 0x06064b50;
28constexpr std::uint32_t kCentralEntry = 0x02014b50;
29constexpr std::uint32_t kLocalHeader = 0x04034b50;
31constexpr std::uint64_t kMetadataLimit = 1 << 20;
32
33std::uint64_t little(const std::string& bytes, std::size_t at, int width)
34{
35 if (at + static_cast<std::size_t>(width) > bytes.size())
36 throw std::out_of_range("truncated zip record");
37 std::uint64_t value = 0;
38 for (int b = width - 1; b >= 0; --b)
39 value = (value << 8) | static_cast<unsigned char>(
40 bytes[at + static_cast<std::size_t>(b)]);
41 return value;
42}
43
44std::string readAt(std::ifstream& file, std::uint64_t offset,
45 std::uint64_t count)
46{
47 std::string bytes(static_cast<std::size_t>(count), '\0');
48 file.clear();
49 file.seekg(static_cast<std::streamoff>(offset));
50 file.read(bytes.data(), static_cast<std::streamsize>(count));
51 bytes.resize(static_cast<std::size_t>(file.gcount()));
52 return bytes;
53}
54
55bool endsWith(const std::string& text, const std::string& suffix)
56{
57 return text.size() >= suffix.size() &&
58 text.compare(text.size() - suffix.size(), suffix.size(), suffix) ==
59 0;
60}
61
63std::string jsonString(const std::string& json, const std::string& key)
64{
65 const std::string quoted = "\"" + key + "\"";
66 std::size_t at = json.find(quoted);
67 if (at == std::string::npos) return {};
68 at = json.find(':', at + quoted.size());
69 if (at == std::string::npos) return {};
70 at = json.find('"', at + 1);
71 if (at == std::string::npos) return {};
72 const std::size_t end = json.find('"', at + 1);
73 if (end == std::string::npos) return {};
74 return json.substr(at + 1, end - at - 1);
75}
76
78std::vector<std::string> metadataEntries(const std::string& path)
79{
80 std::ifstream file(path, std::ios::binary);
81 if (!file) throw std::runtime_error("cannot open model package " + path);
82 file.seekg(0, std::ios::end);
83 const auto size = static_cast<std::uint64_t>(file.tellg());
84 std::vector<std::string> entries;
85 if (size < 22) return entries;
86 // The end record sits within the last 22 + 65535 (comment) bytes.
87 const std::uint64_t tail_size = std::min<std::uint64_t>(size, 22 + 65535);
88 const std::string tail = readAt(file, size - tail_size, tail_size);
89 std::size_t end = std::string::npos;
90 for (std::size_t at = tail.size() - 22 + 1; at-- > 0;)
91 if (little(tail, at, 4) == kEndOfCentralDirectory) {
92 end = at;
93 break;
94 }
95 if (end == std::string::npos) return entries;
96 std::uint64_t count = little(tail, end + 10, 2);
97 std::uint64_t directory_size = little(tail, end + 12, 4);
98 std::uint64_t directory = little(tail, end + 16, 4);
99 if ((count == 0xffff || directory == 0xffffffff ||
100 directory_size == 0xffffffff) &&
101 end >= 20 && little(tail, end - 20, 4) == kZip64Locator) {
102 const std::uint64_t record = little(tail, end - 20 + 8, 8);
103 const std::string zip64 = readAt(file, record, 56);
104 if (zip64.size() == 56 &&
105 little(zip64, 0, 4) == kZip64EndOfCentralDirectory) {
106 count = little(zip64, 32, 8);
107 directory_size = little(zip64, 40, 8);
108 directory = little(zip64, 48, 8);
109 }
110 }
111 if (directory + directory_size > size) return entries;
112 const std::string listing = readAt(file, directory, directory_size);
113 std::size_t at = 0;
114 for (std::uint64_t entry = 0; entry < count; ++entry) {
115 if (at + 46 > listing.size() || little(listing, at, 4) != kCentralEntry)
116 break;
117 const auto method = little(listing, at + 10, 2);
118 std::uint64_t stored = little(listing, at + 20, 4);
119 std::uint64_t original = little(listing, at + 24, 4);
120 const auto name_length =
121 static_cast<std::size_t>(little(listing, at + 28, 2));
122 const auto extra_length =
123 static_cast<std::size_t>(little(listing, at + 30, 2));
124 const auto comment_length =
125 static_cast<std::size_t>(little(listing, at + 32, 2));
126 std::uint64_t local = little(listing, at + 42, 4);
127 const std::string name = listing.substr(at + 46, name_length);
128 // ZIP64 extra field: the 64-bit values of the fields set to ~0.
129 for (std::size_t extra = at + 46 + name_length;
130 extra + 4 <= at + 46 + name_length + extra_length;) {
131 const auto id = little(listing, extra, 2);
132 const auto length =
133 static_cast<std::size_t>(little(listing, extra + 2, 2));
134 if (id == 0x0001) {
135 std::size_t field = extra + 4;
136 if (original == 0xffffffff) {
137 original = little(listing, field, 8);
138 field += 8;
139 }
140 if (stored == 0xffffffff) {
141 stored = little(listing, field, 8);
142 field += 8;
143 }
144 if (local == 0xffffffff) local = little(listing, field, 8);
145 }
146 extra += 4 + length;
147 }
148 at += 46 + name_length + extra_length + comment_length;
149 if (!endsWith(name, "_metadata.json") || method != 0 ||
150 stored != original || stored > kMetadataLimit)
151 continue;
152 const std::string header = readAt(file, local, 30);
153 if (header.size() < 30 || little(header, 0, 4) != kLocalHeader)
154 continue;
155 const std::uint64_t data =
156 local + 30 + little(header, 26, 2) + little(header, 28, 2);
157 entries.push_back(readAt(file, data, stored));
158 }
159 return entries;
160}
161
162#if defined(__x86_64__) || defined(__i386__)
163std::uint64_t extendedControlRegister() noexcept
164{
165 std::uint32_t low = 0, high = 0;
166 __asm__ volatile("xgetbv" : "=a"(low), "=d"(high) : "c"(0));
167 return (static_cast<std::uint64_t>(high) << 32) | low;
168}
169#endif
170
171} // namespace
172
174{
175 HostIsa host;
176#if defined(__x86_64__) || defined(__i386__)
177 unsigned a = 0, b = 0, c = 0, d = 0;
178 if (!__get_cpuid(1, &a, &b, &c, &d)) return host;
179 const bool osxsave = c & (1u << 27);
180 const bool avx = c & (1u << 28);
181 const bool fma = c & (1u << 12);
182 const std::uint64_t xcr0 = osxsave ? extendedControlRegister() : 0;
183 // The OS saves YMM (bits 1, 2), the AVX-512 opmask and ZMM state
184 // (bits 5 to 7) and the AMX tile state (bits 17, 18).
185 const bool ymm = (xcr0 & 0x6) == 0x6;
186 const bool zmm = ymm && (xcr0 & 0xe0) == 0xe0;
187 const bool tiles = (xcr0 & (3ull << 17)) == (3ull << 17);
188 if (__get_cpuid_max(0, nullptr) < 7) return host;
189 unsigned leaf7a = 0;
190 __cpuid_count(7, 0, leaf7a, b, c, d);
191 host.fma = ymm && avx && fma;
192 host.avx2 = ymm && avx && (b & (1u << 5));
193 host.avx512f = zmm && (b & (1u << 16));
194 host.avx512dq = zmm && (b & (1u << 17));
195 host.avx512bw = zmm && (b & (1u << 30));
196 host.avx512vl = zmm && (b & (1u << 31));
197 host.avx512_vnni = zmm && (c & (1u << 11));
198 host.amx_bf16 = tiles && (d & (1u << 22));
199 host.amx_tile = tiles && (d & (1u << 24));
200 host.amx_int8 = tiles && (d & (1u << 25));
201 if (leaf7a >= 1) {
202 __cpuid_count(7, 1, a, b, c, d);
203 host.avx512_bf16 = zmm && (a & (1u << 5));
204 }
205#endif
206 return host;
207}
208
210{
211 AotiPackageTarget target;
212 std::vector<std::string> entries;
213 try {
214 entries = metadataEntries(path);
215 } catch (const std::out_of_range&) {
216 // A truncated archive carries no readable metadata; the loader
217 // reports the damaged package itself.
218 return target;
219 }
220 for (const std::string& json: entries) {
221 target.metadata_found = true;
222 if (target.device.empty())
223 target.device = jsonString(json, "AOTI_DEVICE_KEY");
224 std::istringstream words(jsonString(json, "AOTI_CPU_ISA"));
225 for (std::string word; words >> word;) {
226 std::transform(word.begin(), word.end(), word.begin(),
227 [](unsigned char ch) {
228 return static_cast<char>(std::toupper(ch));
229 });
230 if (std::find(target.cpu_isa.begin(), target.cpu_isa.end(), word) ==
231 target.cpu_isa.end())
232 target.cpu_isa.push_back(word);
233 }
234 }
235 return target;
236}
237
238std::vector<std::string> missingIsa(const AotiPackageTarget& target,
239 const HostIsa& host)
240{
241 std::vector<std::string> missing;
242 for (const std::string& token: target.cpu_isa) {
243 bool present = true;
244 if (token == "DEFAULT" || token == "NONE")
245 present = true;
246 else if (token == "AVX2")
247 present = host.avx2 && host.fma;
248 else if (token == "AVX512")
249 present =
250 host.avx512f && host.avx512dq && host.avx512bw && host.avx512vl;
251 else if (token == "AVX512_VNNI")
252 present = host.avx512_vnni;
253 else if (token == "AVX512_BF16")
254 present = host.avx512_bf16;
255 else if (token == "AMX" || token == "AMX_TILE")
256 present = host.amx_tile;
257 else if (token == "AMX_BF16")
258 present = host.amx_bf16;
259 else if (token == "AMX_INT8")
260 present = host.amx_int8;
261 else {
262 missing.push_back("unknown:" + token);
263 continue;
264 }
265 if (!present) missing.push_back(token);
266 }
267 return missing;
268}
269
270void requireAotiPackageRunsOn(const std::string& path, const HostIsa& host)
271{
272 // A model that cannot be read is the loader's to report, with its own
273 // message; this check only refuses packages it can read.
274 std::error_code ignored;
275 if (!std::filesystem::is_regular_file(path, ignored)) return;
276 const AotiPackageTarget target = readAotiPackageTarget(path);
277 if (!target.metadata_found || target.cpu_isa.empty()) return;
278 std::string lacking, unknown;
279 for (const std::string& token: missingIsa(target, host)) {
280 if (token.rfind("unknown:", 0) == 0)
281 unknown += (unknown.empty() ? "" : " ") + token.substr(8);
282 else
283 lacking += (lacking.empty() ? "" : " ") + token;
284 }
285 if (!unknown.empty())
286 std::cerr << "[model] " << path << " names CPU extensions this check "
287 << "does not know (" << unknown
288 << "); loading it unchecked\n";
289 if (lacking.empty()) return;
290 std::string isa;
291 for (const std::string& token: target.cpu_isa)
292 isa += (isa.empty() ? "" : " ") + token;
293 std::string available;
294 const std::pair<const char*, bool> extensions[] = {
295 {"AVX2", host.avx2 && host.fma},
296 {"AVX512",
297 host.avx512f && host.avx512dq && host.avx512bw && host.avx512vl},
298 {"AVX512_VNNI", host.avx512_vnni},
299 {"AVX512_BF16", host.avx512_bf16},
300 {"AMX_TILE", host.amx_tile},
301 {"AMX_BF16", host.amx_bf16},
302 {"AMX_INT8", host.amx_int8}};
303 for (const auto& [name, present]: extensions)
304 if (present)
305 available += (available.empty() ? "" : " ") + std::string(name);
306 if (available.empty())
307 available = "none of the vector extensions above SSE";
308 throw std::runtime_error(
309 "model package " + path + " requires CPU extensions " + isa +
310 "; this host provides " + available + " and lacks " + lacking +
311 ", so the package would stop with an illegal instruction. AOTInductor "
312 "packages are compiled per host family: run on a host with " +
313 lacking + " or pass a package exported on this host family");
314}
315
316void requireAotiPackageRunsOnHost(const std::string& path)
317{
319}
320
321} // namespace pot
Host check for the instruction set an AOTInductor package needs.
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
Potential wrappers and the batched oracle interface.
AotiPackageTarget readAotiPackageTarget(const std::string &path)
std::vector< std::string > missingIsa(const AotiPackageTarget &target, const HostIsa &host)
void requireAotiPackageRunsOnHost(const std::string &path)
void requireAotiPackageRunsOn(const std::string &path, const HostIsa &host)
requireAotiPackageRunsOnHost against an explicit host description.
The fields of an AOTInductor package that name the hardware it targets.
std::string device
AOTI_DEVICE_KEY, e.g. "cpu" or "cuda".
bool metadata_found
any *_metadata.json entry read
std::vector< std::string > cpu_isa
AOTI_CPU_ISA tokens, upper case.
static HostIsa detect() noexcept
CPUID and XGETBV of the calling host; all false off x86-64.