feat(cuda): make the GPU architecture configurable, native by default

nvcc ran with -arch=sm_89 for every build, which is code for that one
architecture and its PTX, whatever GPU the program was for. Jorijn asked
for the architecture to be configurable, and native when nothing sets
it, as the CPU's is.

cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc
compiles for the GPUs it sees, and where it sees none it warns and uses
its own default architecture. Like -march=native it is for a program
that runs where it is built, since it carries no PTX, and
`crafter-build bundle` warns of a bundle whose CUDA code, in the program
or a library it is built on, is compiled for native, as it warns of
-march=native. ApplyStandardArgs sets it from --cuda-arch= and
CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and
CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the
parent's, as they give them its sysroot and debug flag; and
ForceHostTooling gives host tooling the host's, as it gives it the
host's march, since project.so runs it on the machine that loads it.

A .cu is compiled again only when it is newer than its object, so the
architecture keys VariantId, and so does the nvcc that compiles it, by
what it is rather than where: Toolchain::nvccStamp, its canonical path,
size and time, read without a process, changes when CUDA_PATH names
another toolkit and when an update replaces the one at the same path, as
a package does at /opt/cuda. native is keyed as well, by
Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI
address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER,
which choose and number them, each empty value apart from an unset one,
read without a process. It is crafter-build's reading of the machine,
not nvcc's. The word alone would keep an object compiled for a GPU the
machine no longer has, after a GPU change or on another machine that
shares the checkout, and that object carries no PTX for the GPU it has
now, where sm_89's carried its PTX. Only a configuration with CUDA
sources is keyed, so every other one keeps the directory it had, but for
one built with --cuda-arch=, which was a project argument, hashed as
one, and is crafter-build's own now.
This commit is contained in:
Jorijn van der Graaf 2026-11-11 19:34:52 +01:00
commit 967dd12b06
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
10 changed files with 262 additions and 15 deletions

View file

@ -122,7 +122,7 @@ Beyond the rules:
- There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests. - There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests.
- A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. - A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`.
- Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`. - Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`.
- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`) and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. - Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory.
## Design rules ## Design rules

View file

@ -1145,7 +1145,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// Still .cu-mtime only: the header tracking the C and C++ paths get // Still .cu-mtime only: the header tracking the C and C++ paths get
// comes from asking the compiler for a depfile, and nvcc's -MD/-MF are // comes from asking the compiler for a depfile, and nvcc's -MD/-MF are
// untested here (no CUDA toolkit in CI), so a .cu that only sees a // untested here (no CUDA toolkit in CI), so a .cu that only sees a
// changed header does not rebuild yet. // changed header does not rebuild yet. cfg.cudaArch needs no check:
// it is part of VariantId, so another one builds in another directory.
if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath))) { if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath))) {
const Toolchain& toolchain = GetToolchain(); const Toolchain& toolchain = GetToolchain();
if (toolchain.nvcc.empty()) { if (toolchain.nvcc.empty()) {
@ -1155,11 +1156,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
} }
break; break;
} }
threads.emplace_back([&cFile, &buildError, &buildCancelled, &toolchain, srcPath, objPath]() { threads.emplace_back([&cFile, &buildError, &buildCancelled, &config, &toolchain, srcPath, objPath]() {
Progress::Task task(std::format("Compiling {}.cu", cFile.filename().string())); Progress::Task task(std::format("Compiling {}.cu", cFile.filename().string()));
if (buildCancelled.load(std::memory_order_relaxed)) return; if (buildCancelled.load(std::memory_order_relaxed)) return;
std::string result = RunBuildCommand(std::format("{} {} -c -o {} -O3 -arch=sm_89", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(objPath))); std::string result = RunBuildCommand(std::format("{} {} -c -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(objPath), ShellQuote(config.cudaArch)));
if (result.empty()) return; if (result.empty()) return;
bool expected = false; bool expected = false;
@ -1739,6 +1740,21 @@ std::string Crafter::InstallFlatpakApp(const Configuration& config) {
return ""; return "";
} }
namespace {
// CUDA sources compiled for native, code for the GPUs of the machine
// that builds and no PTX, in `config`'s program: its own, and those of
// every library Build hands its link, which it does through an
// executable dependency too. That executable's own objects are run by
// path and stay out of the bundle; `linked` is false for them alone,
// and it follows from a configuration's type, so `seen` holds either
// way.
bool HasNativeCuda(const Configuration& config, std::unordered_set<const Configuration*>& seen, bool linked = true) {
if (!seen.insert(&config).second) return false;
if (linked && !config.cuda.empty() && config.cudaArch == "native") return true;
return std::ranges::any_of(config.dependencies, [&seen](const Configuration* dep) { return HasNativeCuda(*dep, seen, dep->type != ConfigurationType::Executable); });
}
}
std::string Crafter::BundleFlatpakApp(const Configuration& config) { std::string Crafter::BundleFlatpakApp(const Configuration& config) {
if (const std::string refused = CannotExport(config, "bundle"); !refused.empty()) return refused; if (const std::string refused = CannotExport(config, "bundle"); !refused.empty()) return refused;
const FlatpakExport app = ExportOf(config); const FlatpakExport app = ExportOf(config);
@ -1753,6 +1769,9 @@ std::string Crafter::BundleFlatpakApp(const Configuration& config) {
if (config.march == "native") { if (config.march == "native") {
Progress::Diagnostic(std::format("{} is built with -march=native, so it may stop with SIGILL on a CPU older than this one; for others, build with --march=x86-64-v3", bundle.string())); Progress::Diagnostic(std::format("{} is built with -march=native, so it may stop with SIGILL on a CPU older than this one; for others, build with --march=x86-64-v3", bundle.string()));
} }
if (std::unordered_set<const Configuration*> seen; HasNativeCuda(config, seen)) {
Progress::Diagnostic(std::format("{} holds CUDA code built with --cuda-arch=native, for this machine's GPUs and with no PTX, so it may not run on another machine's GPU; for others, build with --cuda-arch=all-major", bundle.string()));
}
if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("\nBundled {} as {}: `flatpak install --user {}` installs it.", app.appId, bundle.string(), bundle.filename().string()); if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("\nBundled {} as {}: `flatpak install --user {}` installs it.", app.appId, bundle.string(), bundle.filename().string());
return ""; return "";
} }
@ -2000,6 +2019,9 @@ ArgQuery Crafter::ApplyStandardArgs(Configuration& cfg, std::span<const std::str
if (const char* envMtune = std::getenv("CRAFTER_BUILD_MTUNE"); envMtune && *envMtune) { if (const char* envMtune = std::getenv("CRAFTER_BUILD_MTUNE"); envMtune && *envMtune) {
cfg.mtune = envMtune; cfg.mtune = envMtune;
} }
if (const char* envCudaArch = std::getenv("CRAFTER_BUILD_CUDA_ARCH"); envCudaArch && *envCudaArch) {
cfg.cudaArch = envCudaArch;
}
bool sawLib = false; bool sawLib = false;
bool sawShared = false; bool sawShared = false;
for (std::string_view a : args) { for (std::string_view a : args) {
@ -2009,6 +2031,7 @@ ArgQuery Crafter::ApplyStandardArgs(Configuration& cfg, std::span<const std::str
else if (a.starts_with("--target=")) cfg.target = std::string(a.substr(std::string_view("--target=").size())); else if (a.starts_with("--target=")) cfg.target = std::string(a.substr(std::string_view("--target=").size()));
else if (a.starts_with("--march=")) cfg.march = std::string(a.substr(std::string_view("--march=").size())); else if (a.starts_with("--march=")) cfg.march = std::string(a.substr(std::string_view("--march=").size()));
else if (a.starts_with("--mtune=")) cfg.mtune = std::string(a.substr(std::string_view("--mtune=").size())); else if (a.starts_with("--mtune=")) cfg.mtune = std::string(a.substr(std::string_view("--mtune=").size()));
else if (a.starts_with("--cuda-arch=")) cfg.cudaArch = std::string(a.substr(std::string_view("--cuda-arch=").size()));
else if (a.starts_with("--sysroot=")) cfg.sysroot = std::string(a.substr(std::string_view("--sysroot=").size())); else if (a.starts_with("--sysroot=")) cfg.sysroot = std::string(a.substr(std::string_view("--sysroot=").size()));
else if (a.starts_with("--packaging=")) { else if (a.starts_with("--packaging=")) {
const std::string_view kind = a.substr(std::string_view("--packaging=").size()); const std::string_view kind = a.substr(std::string_view("--packaging=").size());
@ -2210,14 +2233,17 @@ Project args:
Any flag not consumed above is forwarded verbatim to CrafterBuildProject as Any flag not consumed above is forwarded verbatim to CrafterBuildProject as
part of its `args` span. Project-specific flags (e.g. --target=, custom part of its `args` span. Project-specific flags (e.g. --target=, custom
feature toggles) live there. ApplyStandardArgs reads --debug, --target=, feature toggles) live there. ApplyStandardArgs reads --debug, --target=,
--march=, --mtune=, --sysroot=, --lib, --shared and --packaging=none|flatpak, --march=, --mtune=, --cuda-arch=, --sysroot=, --lib, --shared and
the last for the project crafter-build was pointed at only. Flags it does not --packaging=none|flatpak, the last for the project crafter-build was pointed
itself interpret are folded into the variant hash, so switching one lands in at only. Flags it does not itself interpret are folded into the variant
its own bin/ and build/ directory instead of overwriting the other setting's. hash, so switching one lands in its own bin/ and build/ directory instead of
overwriting the other setting's.
Environment: Environment:
CRAFTER_BUILD_MARCH Override -march (default: native). CRAFTER_BUILD_MARCH Override -march (default: native).
CRAFTER_BUILD_MTUNE Override -mtune (default: native). CRAFTER_BUILD_MTUNE Override -mtune (default: native).
CRAFTER_BUILD_CUDA_ARCH Override nvcc's -arch for cfg.cuda
(default: native).
CUDA_PATH CUDA toolkit whose bin/nvcc compiles CUDA_PATH CUDA toolkit whose bin/nvcc compiles
cfg.cuda. Default: /opt/cuda, then cfg.cuda. Default: /opt/cuda, then
/usr/local/cuda (in the Flatpak, the /usr/local/cuda (in the Flatpak, the

View file

@ -482,13 +482,14 @@ namespace {
// compiles project.so with, so the dependency's std/Crafter.Build PCMs // compiles project.so with, so the dependency's std/Crafter.Build PCMs
// land in the cache dir project.so is built against. Recursive, because // land in the cache dir project.so is built against. Recursive, because
// the dependency's project.cpp is loaded with no arguments and so passes // the dependency's project.cpp is loaded with no arguments and so passes
// none on, while its own deps still read CRAFTER_BUILD_MARCH from the // none on, while its own deps still read CRAFTER_BUILD_MARCH and
// environment. // CRAFTER_BUILD_CUDA_ARCH from the environment.
void ForceHostTooling(Configuration& cfg, const Configuration& host, std::unordered_set<Configuration*>& seen) { void ForceHostTooling(Configuration& cfg, const Configuration& host, std::unordered_set<Configuration*>& seen) {
if (!seen.insert(&cfg).second) return; if (!seen.insert(&cfg).second) return;
cfg.target = host.target; cfg.target = host.target;
cfg.march = host.march; cfg.march = host.march;
cfg.mtune = host.mtune; cfg.mtune = host.mtune;
cfg.cudaArch = host.cudaArch;
cfg.debug = false; cfg.debug = false;
// project.so is a shared object, so the archive it links has to be // project.so is a shared object, so the archive it links has to be
// position-independent; static libraries aren't by default. Part of // position-independent; static libraries aren't by default. Part of

View file

@ -370,6 +370,7 @@ TestBuilder Configuration::AddTest(std::string_view name, std::span<fs::path> in
t.config.mtune = this->mtune; t.config.mtune = this->mtune;
t.config.sysroot = this->sysroot; t.config.sysroot = this->sysroot;
t.config.debug = this->debug; t.config.debug = this->debug;
t.config.cudaArch = this->cudaArch;
// Inherited so a project flag that changes what the library contains also // Inherited so a project flag that changes what the library contains also
// moves the test's own outputs, rather than letting two flag settings share // moves the test's own outputs, rather than letting two flag settings share
// one test bin dir. // one test bin dir.
@ -398,6 +399,7 @@ void Configuration::AddMarchVariants(std::string_view name, std::span<fs::path>
t.config.mtune = tier.mtune; t.config.mtune = tier.mtune;
t.config.sysroot = this->sysroot; t.config.sysroot = this->sysroot;
t.config.debug = this->debug; t.config.debug = this->debug;
t.config.cudaArch = this->cudaArch;
t.config.projectArgs = this->projectArgs; t.config.projectArgs = this->projectArgs;
t.config.type = ConfigurationType::Executable; t.config.type = ConfigurationType::Executable;

View file

@ -309,6 +309,45 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) {
tc.nvccError = std::format("no CUDA toolkit found: looked for {}; set CUDA_PATH to the directory a toolkit is installed in", places); tc.nvccError = std::format("no CUDA toolkit found: looked for {}; set CUDA_PATH to the directory a toolkit is installed in", places);
} }
} }
// What VariantId keys a CUDA configuration's nvcc by. Its path stays
// when the toolkit behind it is updated, by a package at /opt/cuda or by
// /usr/local/cuda pointed at another release, and the objects the old
// nvcc compiled would be kept. The binary's canonical path, size and
// time change with it, and reading them starts no process.
if (!tc.nvcc.empty()) {
std::error_code ec;
fs::path real = fs::canonical(tc.nvcc, ec);
if (ec) real = tc.nvcc;
const std::uintmax_t size = fs::file_size(real, ec);
const auto time = fs::last_write_time(real, ec).time_since_epoch().count();
tc.nvccStamp = std::format("{}|{}|{}", real.string(), size, time);
}
// What VariantId keys -arch=native by: nvcc compiles it for the GPUs it
// finds, so a GPU of another model, the same GPUs in each other's slots,
// or CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER choosing another or,
// empty, none, has to build in a directory of its own, where the word
// alone would keep an object compiled for the old GPU, with no PTX for the
// new one. The NVIDIA display devices (class 0x03) by PCI address and
// device ID, in the order of their addresses, from sysfs, which starts no
// process; an entry that cannot be read counts as none, and nothing here
// throws. It is crafter-build's reading of the machine, not nvcc's: a
// change it cannot see, such as a GPU bound to another driver, keeps the
// key.
if (!tc.nvcc.empty()) {
std::vector<std::string> gpus;
std::error_code ec;
for (fs::directory_iterator it(in.pciDevices, ec), end; !ec && it != end; it.increment(ec)) {
const auto field = [&it](std::string_view name) {
std::string value;
std::ifstream(it->path() / name) >> value;
return value;
};
if (field("vendor") == "0x10de" && field("class").starts_with("0x03")) gpus.push_back(std::format("{}={}", it->path().filename().string(), field("device")));
}
std::ranges::sort(gpus);
const auto spelled = [](const std::optional<std::string>& value) { return value ? std::format("={}", *value) : std::string("unset"); };
tc.cudaNativeKey = std::format("{}|{}|{}", std::views::join_with(gpus, std::string(",")) | std::ranges::to<std::string>(), spelled(in.cudaVisibleDevices), spelled(in.cudaDeviceOrder));
}
std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo); std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo);
return tc; return tc;
} }
@ -328,6 +367,9 @@ const Toolchain& Crafter::GetToolchain() {
} catch (const std::exception&) {} } catch (const std::exception&) {}
if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host"; if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host";
in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" }; in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" };
in.pciDevices = "/sys/bus/pci/devices";
if (const char* value = std::getenv("CUDA_VISIBLE_DEVICES")) in.cudaVisibleDevices = value;
if (const char* value = std::getenv("CUDA_DEVICE_ORDER")) in.cudaDeviceOrder = value;
{ {
auto it = in.env.find("CRAFTER_BUILD_FLATPAK_INFO"); auto it = in.env.find("CRAFTER_BUILD_FLATPAK_INFO");
const fs::path info = it != in.env.end() ? fs::path(it->second) : fs::path("/.flatpak-info"); const fs::path info = it != in.env.end() ? fs::path(it->second) : fs::path("/.flatpak-info");

View file

@ -504,6 +504,16 @@ export namespace Crafter {
std::vector<Implementation> implementations; std::vector<Implementation> implementations;
std::vector<fs::path> cFiles; std::vector<fs::path> cFiles;
std::vector<fs::path> cuda; std::vector<fs::path> cuda;
// The GPU architecture nvcc compiles `cuda` for, as its -arch takes
// one. "native", the default, compiles for the GPUs of the machine
// that builds, as march's default does for its CPU; with none to be
// seen, nvcc warns and uses its own default. Like -march=native it is
// for a program that runs where it is built: it carries no PTX, which
// a newer GPU could compile when it loads the program. "sm_89" is one
// architecture with its PTX; "all-major" or "all" is for a program
// that runs elsewhere. ApplyStandardArgs sets it from
// CRAFTER_BUILD_CUDA_ARCH and --cuda-arch=.
std::string cudaArch = "native";
std::vector<Configuration*> dependencies; std::vector<Configuration*> dependencies;
std::vector<fs::path> files; std::vector<fs::path> files;
// Build-time-only source files this configuration exposes to its own // Build-time-only source files this configuration exposes to its own
@ -593,9 +603,9 @@ export namespace Crafter {
void ResolvePendingImports(); void ResolvePendingImports();
// Declare a test. Sources default to `tests/<name>/main.cpp` resolved // Declare a test. Sources default to `tests/<name>/main.cpp` resolved
// against this Configuration's path; target/march/mtune/sysroot/debug // against this Configuration's path; target/march/mtune/sysroot/debug
// are inherited from this Configuration so cross-arch projects don't // and cudaArch are inherited from this Configuration so cross-arch
// have to re-specify. Returns a builder for chaining defines, deps, // projects don't have to re-specify. Returns a builder for chaining
// etc. Defined in Crafter.Build:Test. // defines, deps, etc. Defined in Crafter.Build:Test.
struct TestBuilder AddTest(std::string_view name); struct TestBuilder AddTest(std::string_view name);
// Same as AddTest, but compiles the parent's `interfaces` directly // Same as AddTest, but compiles the parent's `interfaces` directly
// into this test's Configuration (rather than going through a dep). // into this test's Configuration (rather than going through a dep).
@ -625,7 +635,7 @@ export namespace Crafter {
// Suffix that uniquely identifies this Configuration's compile state. // Suffix that uniquely identifies this Configuration's compile state.
// target+march+mtune are spelled out for readability; the rest // target+march+mtune are spelled out for readability; the rest
// (type, debug, sysroot, defines, compileFlags, the std module, the // (type, debug, sysroot, defines, compileFlags, the std module, the
// toolchain) // toolchain, the GPU architecture and the nvcc of CUDA sources)
// collapse into a short hash so two Configurations sharing a path but // collapse into a short hash so two Configurations sharing a path but
// with different compile state can't clobber each other's outputs. // with different compile state can't clobber each other's outputs.
std::string VariantId() const { return VariantId(GetToolchain()); } std::string VariantId() const { return VariantId(GetToolchain()); }
@ -690,6 +700,25 @@ export namespace Crafter {
} }
compileKey += "|T:"; compileKey += "|T:";
compileKey += toolchain.Key(); compileKey += toolchain.Key();
// The GPU architecture decides what a .cu compiles into, and so
// does the toolkit whose nvcc compiles it, which CUDA_PATH can
// switch and an update can replace at the same path, so the nvcc
// is keyed by what it is (Toolchain::nvccStamp), and native by the
// GPUs it resolves to (Toolchain::cudaNativeKey). None of them
// need touch the files whose times decide whether a .cu is
// compiled again, so each needs a directory of its own. Only keyed
// with CUDA sources, so every other configuration keeps the
// directory it had.
if (!cuda.empty()) {
compileKey += "|C:";
compileKey += cudaArch;
compileKey += '|';
compileKey += toolchain.nvccStamp;
if (cudaArch == "native") {
compileKey += '|';
compileKey += toolchain.cudaNativeKey;
}
}
// A Flatpak lays its bin dir out unlike the executable as linked, // A Flatpak lays its bin dir out unlike the executable as linked,
// so the two never share one. Only keyed for a Flatpak, so every // so the two never share one. Only keyed for a Flatpak, so every
// other configuration keeps the directory it had. // other configuration keeps the directory it had.
@ -867,6 +896,7 @@ export namespace Crafter {
// --target=<triple> cfg.target = <triple> // --target=<triple> cfg.target = <triple>
// --march=<value> cfg.march = <value> // --march=<value> cfg.march = <value>
// --mtune=<value> cfg.mtune = <value> // --mtune=<value> cfg.mtune = <value>
// --cuda-arch=<value> cfg.cudaArch = <value>
// --lib cfg.type promoted Executable → LibraryStatic // --lib cfg.type promoted Executable → LibraryStatic
// --shared cfg.type promoted LibraryStatic → LibraryDynamic // --shared cfg.type promoted LibraryStatic → LibraryDynamic
// --packaging=<kind> cfg.packaging = None or Flatpak (none, flatpak), // --packaging=<kind> cfg.packaging = None or Flatpak (none, flatpak),
@ -878,7 +908,8 @@ export namespace Crafter {
// LibraryDynamic regardless of arg order; each is a no-op when the // LibraryDynamic regardless of arg order; each is a no-op when the
// baseline doesn't match (e.g. --shared on an Executable, or --lib on a // baseline doesn't match (e.g. --shared on an Executable, or --lib on a
// pre-set library). // pre-set library).
// $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE seed march/mtune. // $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE / $CRAFTER_BUILD_CUDA_ARCH
// seed march/mtune/cudaArch.
// Env applies first, then args, so CLI wins over env wins over caller's // Env applies first, then args, so CLI wins over env wins over caller's
// pre-set defaults. Returns an ArgQuery over the same span so projects // pre-set defaults. Returns an ArgQuery over the same span so projects
// can query their own flags (`--timing`, ...) without re-rolling the // can query their own flags (`--timing`, ...) without re-rolling the

View file

@ -67,6 +67,17 @@ export namespace Crafter {
// for want of a CUDA toolkit. // for want of a CUDA toolkit.
fs::path nvcc; fs::path nvcc;
std::string nvccError; std::string nvccError;
// What that nvcc is, for VariantId: its canonical path, size and
// modification time, which change when the toolkit is updated or
// replaced at the same path, as the path alone does not. Empty
// without an nvcc.
std::string nvccStamp;
// What -arch=native compiles for on this machine, for VariantId: the
// NVIDIA display devices the PCI bus lists, by address and device ID,
// and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose among
// them and number them, each unset apart from empty. Empty without an
// nvcc.
std::string cudaNativeKey;
// The Flatpak runtime crafter-build runs on, from the // The Flatpak runtime crafter-build runs on, from the
// runtime=runtime/<id>/<arch>/<branch> line of /.flatpak-info: // runtime=runtime/<id>/<arch>/<branch> line of /.flatpak-info:
// "x86_64" and "26.08" in the Flatpak, both empty outside one. A // "x86_64" and "26.08" in the Flatpak, both empty outside one. A
@ -125,6 +136,19 @@ export namespace Crafter {
// order they are tried and as the host names them: GetToolchain() // order they are tried and as the host names them: GetToolchain()
// passes /opt/cuda, Arch's, and /usr/local/cuda, NVIDIA's installers'. // passes /opt/cuda, Arch's, and /usr/local/cuda, NVIDIA's installers'.
std::vector<fs::path> cudaRoots; std::vector<fs::path> cudaRoots;
// The PCI devices sysfs lists, one directory each with its vendor,
// device and class: GetToolchain() passes /sys/bus/pci/devices, which
// the sandbox shows too. What -arch=native compiles for is keyed by
// the NVIDIA display devices among them.
fs::path pciDevices;
// CUDA_VISIBLE_DEVICES, which chooses the GPUs -arch=native compiles
// for, when it is set: set but empty hides them all, which is not the
// same as unset, so it is kept apart from env, which holds non-empty
// values alone.
std::optional<std::string> cudaVisibleDevices;
// CUDA_DEVICE_ORDER, when it is set: it decides which GPU a number in
// CUDA_VISIBLE_DEVICES means, by PCI address or by speed.
std::optional<std::string> cudaDeviceOrder;
}; };
// Pure path resolution: an env override wins, then a toolchain installed // Pure path resolution: an env override wins, then a toolchain installed
// beside crafter-build (<crafterPrefix>/bin/clang++), then bare names on // beside crafter-build (<crafterPrefix>/bin/clang++), then bare names on

View file

@ -1,6 +1,7 @@
// SPDX-License-Identifier: LGPL-3.0-only // SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#include <stdlib.h>
import std; import std;
import Crafter.Build; import Crafter.Build;
using namespace Crafter; using namespace Crafter;
@ -33,6 +34,31 @@ int main() {
Check(cfg.mtune == "cortex-a72", "--mtune= should overwrite cfg.mtune"); Check(cfg.mtune == "cortex-a72", "--mtune= should overwrite cfg.mtune");
} }
// --cuda-arch= is nvcc's -arch for cfg.cuda, as --march= is the CPU's,
// and it defaults to native as march does.
{
Configuration plain;
Check(plain.cudaArch == "native", "the GPU architecture defaults to native, like march");
Configuration cfg;
std::array<std::string_view, 1> raw = { "--cuda-arch=all-major" };
ApplyStandardArgs(cfg, raw);
Check(cfg.cudaArch == "all-major", "--cuda-arch= sets cfg.cudaArch");
Check(cfg.projectArgs.empty(), "--cuda-arch= is not a project arg");
}
{
// CRAFTER_BUILD_CUDA_ARCH sets it as CRAFTER_BUILD_MARCH sets march,
// and the command line wins over it.
setenv("CRAFTER_BUILD_CUDA_ARCH", "sm_86", 1);
Configuration fromEnv;
ApplyStandardArgs(fromEnv, {});
Check(fromEnv.cudaArch == "sm_86", "CRAFTER_BUILD_CUDA_ARCH sets cfg.cudaArch");
Configuration both;
std::array<std::string_view, 1> raw = { "--cuda-arch=sm_120" };
ApplyStandardArgs(both, raw);
Check(both.cudaArch == "sm_120", "--cuda-arch= wins over CRAFTER_BUILD_CUDA_ARCH");
unsetenv("CRAFTER_BUILD_CUDA_ARCH");
}
// --sysroot= sets cfg.sysroot (cross-compiles against a foreign root, // --sysroot= sets cfg.sysroot (cross-compiles against a foreign root,
// e.g. an Alpine aarch64 tree; also picked up by the std.cppm lookup // e.g. an Alpine aarch64 tree; also picked up by the std.cppm lookup
// and the qemu test-runner's QEMU_LD_PREFIX). // and the qemu test-runner's QEMU_LD_PREFIX).

View file

@ -302,6 +302,65 @@ int main() {
Check(ResolveToolchain(in).nvcc.empty(), "a link to itself ends, and finds nothing"); Check(ResolveToolchain(in).nvcc.empty(), "a link to itself ends, and finds nothing");
fs::remove_all(host); fs::remove_all(host);
} }
{
// What VariantId keys a CUDA configuration's nvcc by: its canonical
// path, size and time, which an nvcc replaced at its path changes,
// as it does not change the path.
const fs::path toolkit = scratch / "stamped";
Program(toolkit / "bin/nvcc");
ToolchainInputs in;
in.env["CUDA_PATH"] = toolkit.string();
const std::string before = ResolveToolchain(in).nvccStamp;
Check(before.starts_with(std::format("{}|", fs::canonical(toolkit / "bin/nvcc").string())), std::format("the stamp names the nvcc where its links lead (got '{}')", before));
std::ofstream(toolkit / "bin/nvcc", std::ios::app) << "13.5";
Check(ResolveToolchain(in).nvccStamp != before, "an nvcc replaced at its path stamps differently");
Check(ResolveToolchain({}).nvccStamp.empty(), "no nvcc, no stamp");
}
{
// What VariantId keys -arch=native by: the NVIDIA display devices the
// PCI bus lists, by slot and model, and CUDA_VISIBLE_DEVICES and
// CUDA_DEVICE_ORDER. Another GPU, the same GPUs in each other's slots,
// or another choice or numbering among them keys it differently; a
// GPU's audio function, another NVIDIA class, and another vendor's GPU
// do not count.
const fs::path toolkit = scratch / "native/toolkit";
Program(toolkit / "bin/nvcc");
const fs::path pci = scratch / "native/pci";
const auto device = [&pci](std::string_view address, std::string_view vendor, std::string_view id, std::string_view type) {
fs::create_directories(pci / address);
std::ofstream(pci / address / "vendor") << vendor << "\n";
std::ofstream(pci / address / "device") << id << "\n";
std::ofstream(pci / address / "class") << type << "\n";
};
device("0000:34:00.0", "0x10de", "0x2684", "0x030000");
device("0000:34:00.1", "0x10de", "0x22ba", "0x040300");
device("0000:00:02.0", "0x8086", "0xa780", "0x030000");
ToolchainInputs in;
in.env["CUDA_PATH"] = toolkit.string();
in.pciDevices = pci;
const std::string one = ResolveToolchain(in).cudaNativeKey;
Check(one.contains("0x2684") && !one.contains("0x22ba") && !one.contains("0xa780"), std::format("native is keyed by the NVIDIA display devices alone (got '{}')", one));
device("0000:ca:00.0", "0x10de", "0x2b85", "0x030200");
const std::string two = ResolveToolchain(in).cudaNativeKey;
Check(two != one && two.contains("0x2b85"), std::format("another GPU keys it differently (got '{}')", two));
in.cudaVisibleDevices = "1";
const std::string chosen = ResolveToolchain(in).cudaNativeKey;
Check(chosen != two, "and so does CUDA_VISIBLE_DEVICES");
in.cudaVisibleDevices = "";
const std::string hidden = ResolveToolchain(in).cudaNativeKey;
Check(hidden != two && hidden != chosen, std::format("an empty CUDA_VISIBLE_DEVICES, which hides every GPU, keys apart from an unset one (got '{}')", hidden));
in.cudaVisibleDevices.reset();
Check(ResolveToolchain(in).cudaNativeKey == two, "unset again, the key is as it was");
in.cudaDeviceOrder = "PCI_BUS_ID";
Check(ResolveToolchain(in).cudaNativeKey != two, "CUDA_DEVICE_ORDER, which numbers the GPUs, keys it differently");
in.cudaDeviceOrder.reset();
device("0000:34:00.0", "0x10de", "0x2b85", "0x030200");
device("0000:ca:00.0", "0x10de", "0x2684", "0x030000");
const std::string swapped = ResolveToolchain(in).cudaNativeKey;
Check(swapped != two, std::format("so do the same GPUs in each other's slots (got '{}')", swapped));
in.env.erase("CUDA_PATH");
Check(ResolveToolchain(in).cudaNativeKey.empty(), "no nvcc, no key");
}
{ {
// The cache key separates toolchains that would build different // The cache key separates toolchains that would build different
// PCMs and nothing else. // PCMs and nothing else.

View file

@ -128,6 +128,42 @@ int main() {
b.march = "x86-64-v3"; b.march = "x86-64-v3";
Check(a.VariantId() != b.VariantId(), "march change perturbs VariantId"); Check(a.VariantId() != b.VariantId(), "march change perturbs VariantId");
} }
{
// The GPU architecture decides what a .cu compiles into, and it need
// not touch the files whose times decide whether a .cu is compiled
// again, so it keys the directory of a configuration with CUDA
// sources, and only of one.
Configuration a = MakeBase();
a.cuda = { "/tmp/variant-id-test/kernel" };
Configuration b = MakeBase();
b.cuda = a.cuda;
b.cudaArch = "sm_89";
Check(a.VariantId() != b.VariantId(), "cudaArch change perturbs the VariantId of a configuration with CUDA sources");
Configuration c = MakeBase();
Configuration d = MakeBase();
d.cudaArch = "sm_89";
Check(c.VariantId() == d.VariantId(), "without CUDA sources, cudaArch leaves VariantId alone");
// So does the nvcc that compiles them, by what it is: CUDA_PATH can
// name another toolkit, and an update can replace one at its path,
// and the old one's objects must not pass for the new one's.
const Toolchain one = GetToolchain();
Toolchain other = one;
other.nvccStamp = "/opt/other-cuda/bin/nvcc|1|1";
Toolchain updated = other;
updated.nvccStamp = "/opt/other-cuda/bin/nvcc|2|2";
Check(a.VariantId(one) != a.VariantId(other), "another nvcc perturbs the VariantId of a configuration with CUDA sources");
Check(a.VariantId(other) != a.VariantId(updated), "so does an nvcc updated at the same path");
Check(c.VariantId(one) == c.VariantId(other), "without CUDA sources, the nvcc leaves VariantId alone");
// native is what nvcc finds on the machine, so the GPUs it finds key
// it as well, and only it.
Toolchain first = one;
first.cudaNativeKey = "0x2684|";
Toolchain swapped = one;
swapped.cudaNativeKey = "0x2b85|";
Check(a.VariantId(first) != a.VariantId(swapped), "another GPU perturbs the VariantId of a configuration with CUDA sources for native");
Check(b.VariantId(first) == b.VariantId(swapped), "but not for a named architecture");
Check(c.VariantId(first) == c.VariantId(swapped), "nor without CUDA sources");
}
{ {
// A project flag the framework can't interpret still decides what gets // A project flag the framework can't interpret still decides what gets
// compiled and bundled, so it has to key into VariantId. Otherwise both // compiled and bundled, so it has to key into VariantId. Otherwise both