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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions terminal/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6337,7 +6337,7 @@ def build_engine_hip(gpu, llama, vision="none", portable=False) -> Path:
"-DSTRATA_Q6K_EXPERTS=ON", "-DCMAKE_HIP_ARCHITECTURES=" + ";".join(archs),
f"-DCMAKE_HIP_COMPILER={rocm_clang(root)}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}",
"-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]),
f"-DCMAKE_HIP_FLAGS=-isystem {root}/include --rocm-path={root} --rocm-device-lib-path={bitcode}",
f'-DCMAKE_HIP_FLAGS=-isystem "{root}/include" --rocm-path="{root}" --rocm-device-lib-path="{bitcode}"',
f"-DSTRATA_PORTABLE={'ON' if portable else 'OFF'}",
*ggml_defs(llama), *isa_floor_defs(floor, ROOT / "build-hip", meta)], None, "")
if stale_binary(ROOT / "build-hip" / EXE): # #2054: no stamp for a binary of another version
Expand Down Expand Up @@ -6398,7 +6398,7 @@ def build_engine_hip_win(gpu, llama, portable=False) -> Path:
f"-DCMAKE_CXX_COMPILER={rocm}/lib/llvm/bin/clang++.exe",
f"-DCMAKE_HIP_COMPILER={rocm}/lib/llvm/bin/clang++.exe",
f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={rocm}", f"-DCMAKE_PREFIX_PATH={rocm}",
f"-DCMAKE_HIP_FLAGS=--rocm-path={rocm} --rocm-device-lib-path={bitcode}",
f'-DCMAKE_HIP_FLAGS=--rocm-path="{rocm}" --rocm-device-lib-path="{bitcode}"',
*ggml_defs(llama)], vcvars, "build-strata-hip-win.bat")
if stale_binary(bdir / EXE): # #2054: no stamp for a binary of another source
fail(f"the engine build finished without a new engine ({EXE} is version "
Expand Down Expand Up @@ -6474,7 +6474,7 @@ def build_vision_hip(eng: Path, stamp: Path, meta: dict, llama, vsrc, archs: lis
["-DSTRATA_VISION_HIP=ON", "-DSTRATA_VISION_HIP_ARCHS=" + ";".join(archs),
"-DSTRATA_PORTABLE=OFF", f"-DCMAKE_HIP_COMPILER={rocm_clang(root)}",
f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]),
f"-DCMAKE_HIP_FLAGS=-isystem {root}/include --rocm-path={root} --rocm-device-lib-path={bitcode}"], None, "")
f'-DCMAKE_HIP_FLAGS=-isystem "{root}/include" --rocm-path="{root}" --rocm-device-lib-path="{bitcode}"'], None, "")
shutil.copy2(ROOT / "build-vision-hip" / "bin" / HVEXE, eng / HVEXE)
except SystemExit:
raise
Expand Down Expand Up @@ -7520,6 +7520,14 @@ def forward_slash_defs(defs, win: bool | None = None) -> list:
return [d.replace("\\", "/") if win and isinstance(d, str) and d.startswith("-D") else d for d in defs]


def bat_arg(x) -> str:
"""One argument of a command line in the generated build .bat. An argument with a space is quoted; a quote inside it
becomes \\" so the program's argument parser keeps it (#7138: CMAKE_HIP_FLAGS quotes the ROCm paths, which hold the
install folder, so a folder named with a space reaches clang++ as one path)."""
s = str(x)
return '"' + s.replace('"', '\\"') + '"' if (" " in s or '"' in s) else s


def cmake_build(src, bdir, target, defs, vcvars, bat_name):
"""`target`: one CMake target, or a list of them (one `--target` each: the Windows HIP engine builds `strata` and
`strata-device` together, as tools/hip/build_windows.bat does)."""
Expand All @@ -7542,7 +7550,7 @@ def cmake_build(src, bdir, target, defs, vcvars, bat_name):
"install Visual Studio 2022 Build Tools (workload 'Desktop development with C++'), then run setup again; a ready-made engine "
"needs no compiler: `strata update` fetches it")
bat = ROOT / bat_name
q = lambda c: " ".join(f'"{x}"' if " " in str(x) else str(x) for x in c) # noqa: E731
q = lambda c: " ".join(bat_arg(x) for x in c) # noqa: E731
bat.write_bytes((f'@echo off\r\ncall "{vcvars}"{vcvars_toolset(vcvars)} >nul\r\n{q(conf)} || exit /b 1\r\n{q(build)} && exit /b 0\r\n'
f'echo (the build stopped - trying it once more)\r\n{q(build)} || exit /b 1\r\n').encode("utf-8"))
# bytes, not text: the \r\n is written here, and text mode on Windows would turn each one into \r\r\n (#1939)
Expand Down Expand Up @@ -10457,7 +10465,7 @@ def build_engine_poly_hip(gpu, llama, portable=False) -> Path:
"-DCMAKE_HIP_ARCHITECTURES=" + ";".join(archs),
f"-DCMAKE_HIP_COMPILER={rocm_clang(root)}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}",
"-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]),
f"-DCMAKE_HIP_FLAGS=-isystem {root}/include --rocm-path={root} --rocm-device-lib-path={bitcode}",
f'-DCMAKE_HIP_FLAGS=-isystem "{root}/include" --rocm-path="{root}" --rocm-device-lib-path="{bitcode}"',
*ggml_defs(llama)], None, "")
shutil.copy2(ROOT / "build-poly-hip" / POLY_EXE, eng / POLY_EXE)
stamp.write_text(json.dumps({"source": "local-hip", "backend": "hip", "version": source_version(),
Expand Down Expand Up @@ -10508,7 +10516,7 @@ def build_engine_poly_hip_win(gpu, llama, portable=False) -> Path:
f"-DCMAKE_CXX_COMPILER={rocm}/lib/llvm/bin/clang++.exe",
f"-DCMAKE_HIP_COMPILER={rocm}/lib/llvm/bin/clang++.exe",
f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={rocm}", f"-DCMAKE_PREFIX_PATH={rocm}",
f"-DCMAKE_HIP_FLAGS=--rocm-path={rocm} --rocm-device-lib-path={bitcode}",
f'-DCMAKE_HIP_FLAGS=--rocm-path="{rocm}" --rocm-device-lib-path="{bitcode}"',
*ggml_defs(llama)], vcvars, "build-strata-poly-hip.bat")
shutil.copy2(bdir / POLY_EXE, eng / POLY_EXE)
# the DLLs, the GEMM kernels and the .kpack files rocBLAS finds beside its DLL come from the ready-made main
Expand Down
29 changes: 25 additions & 4 deletions terminal/tests/terminal/test_gh_0217_hipflags.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,53 @@
"""0.2.17 GH-LIST #6255 / #6256 (iMilnb): every HIP build the Terminal starts names the chosen ROCm's own include folder before the system's
(`-isystem <root>/include` first in CMAKE_HIP_FLAGS), so a distro's older HIP headers in /usr/include never pair with the chosen ROCm's compiler.
The flag strings are read from the source (no ROCm, no compiler here)."""
#7138: every path in those flags is quoted, so an install folder named with a space reaches clang++ as one path; the Windows build .bat
keeps the quotes (setup.bat_arg). The flag strings are read from the source (no ROCm, no compiler here)."""

from __future__ import annotations

import re
import unittest
from pathlib import Path

import setup

TERMINAL = Path(__file__).resolve().parents[2]


class HipFlagsNameTheRootFirst(unittest.TestCase):
def flags(self, relative: str) -> list[str]:
text = (TERMINAL / relative).read_text(encoding="utf-8")
return re.findall(r'CMAKE_HIP_FLAGS=([^"\n]*)"', text)
return re.findall(r"CMAKE_HIP_FLAGS=([^'\n]*)'", text)

def test_setup_py_has_the_engine_and_the_picture_reader_builds(self):
# (PolyStrata) and strata-poly's Linux build; the Windows builds ({rocm}: TheRock's wheels) have no system HIP headers to avoid
found = [f for f in self.flags("setup.py") if "{root}" in f]
self.assertEqual(len(found), 3, found)
for flags in found:
self.assertTrue(flags.startswith("-isystem {root}/include --rocm-path={root}"), flags)
self.assertTrue(flags.startswith('-isystem "{root}/include" --rocm-path="{root}"'), flags)

def test_the_image_tool_builds_the_same_way(self):
found = self.flags("tools/image/qimage.py")
self.assertEqual(len(found), 1, found)
self.assertTrue(found[0].startswith("-isystem {rocm}/include --rocm-path={rocm}"), found[0])
self.assertTrue(found[0].startswith('-isystem "{rocm}/include" --rocm-path="{rocm}"'), found[0])

def test_every_path_in_the_flags_is_quoted(self):
# #7138: an unquoted {root}, {rocm} or {bitcode} splits at a space in the install folder
found = self.flags("setup.py") + self.flags("tools/image/qimage.py")
self.assertEqual(len(found), 6, found)
for flags in found:
self.assertNotRegex(flags, r'(?<!")\{(root|rocm|bitcode)\}', flags)


class BatArgKeepsAQuotedPathWhole(unittest.TestCase):
def test_plain_arguments_stay_as_they_were(self):
self.assertEqual(setup.bat_arg("-DSTRATA_ENABLE_HIP=ON"), "-DSTRATA_ENABLE_HIP=ON")
self.assertEqual(setup.bat_arg(Path("C:/a b/cmake.exe")), '"' + str(Path("C:/a b/cmake.exe")) + '"')

def test_quotes_inside_an_argument_are_escaped(self):
arg = '-DCMAKE_HIP_FLAGS=--rocm-path="D:/Poly Strata/rocm" --rocm-device-lib-path="D:/Poly Strata/bitcode"'
self.assertEqual(setup.bat_arg(arg),
'"-DCMAKE_HIP_FLAGS=--rocm-path=\\"D:/Poly Strata/rocm\\" --rocm-device-lib-path=\\"D:/Poly Strata/bitcode\\""')


if __name__ == "__main__":
Expand Down
6 changes: 5 additions & 1 deletion terminal/tools/image/gate/build_variant.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@
for c in info["configure"]] + extra
env = dict(os.environ, PATH=info["env_path"])
if backend == "hip": # build_sd.py's ROCm environment (ROCM_PATH / HIP_PATH from the --rocm-path of its HIP flags)
rocm = next((c.split("--rocm-path=", 1)[1].split()[0] for c in info["configure"] if "--rocm-path=" in c), None)
# the path is quoted (#7138), so a folder named with a space stays whole; an unquoted one ends at the next space
def rocm_path(arg: str) -> str:
v = arg.split("--rocm-path=", 1)[1]
return v[1:].split('"', 1)[0] if v.startswith('"') else v.split()[0]
rocm = next((rocm_path(c) for c in info["configure"] if "--rocm-path=" in c), None)
if rocm:
env.update(HIP_PLATFORM="amd", ROCM_PATH=rocm, HIP_PATH=rocm)
if info.get("env_ld"):
Expand Down
2 changes: 1 addition & 1 deletion terminal/tools/image/qimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def cmake_defs(backend: str, arch=None, rocm: Path | None = None, cuda_root: Pat
f"-DCMAKE_C_COMPILER={llvm / 'bin' / 'clang'}", f"-DCMAKE_CXX_COMPILER={llvm / 'bin' / 'clang++'}",
f"-DCMAKE_HIP_COMPILER={llvm / 'bin' / 'clang++'}",
f"-DCMAKE_PREFIX_PATH={rocm};{rocm / 'lib' / 'rocm_sysdeps'};{llvm}",
f"-DCMAKE_HIP_FLAGS=-isystem {rocm}/include --rocm-path={rocm} --rocm-device-lib-path={bitcode}"]
f'-DCMAKE_HIP_FLAGS=-isystem "{rocm}/include" --rocm-path="{rocm}" --rocm-device-lib-path="{bitcode}"']
elif backend == "vulkan":
defs += ["-DSD_VULKAN=ON"]
elif backend != "cpu":
Expand Down
Loading