Skip to content
Merged
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
17 changes: 0 additions & 17 deletions src/hip/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ pub const ATTR_MAX_DYNAMIC_SHARED: c_int = 8;
pub const ATTR_SHARED_PER_BLOCK_OPTIN: c_int = 75;
pub const ATTR_SHARED_PER_BLOCK: c_int = 74;
pub const ATTR_WARP_SIZE: c_int = 87;
pub const ATTR_INTEGRATED: c_int = 16;
pub const ATTR_MULTIPROCESSOR_COUNT: c_int = 63;
pub const ATTR_MAX_THREADS_PER_BLOCK: c_int = 56;

/// Room for `hipDeviceProp_t`, which `hipGetDeviceProperties` writes whole. ROCm 7's `hipDeviceProp_tR0600` is 1472
/// bytes; the size is not exported and changes between versions, so the buffer leaves ample room for a larger one.
Expand All @@ -53,8 +50,6 @@ fn find_gfx(bytes: &[u8]) -> Option<String> {
None
}

type Fn = unsafe extern "C" fn();

/// Library names to try, in order. `STRATA_HIP` (a path or a name) replaces the whole list.
fn candidates(vars: Option<PathBuf>, default_suffix: &[&str]) -> Vec<PathBuf> {
if let Some(p) = vars { return vec![p]; }
Expand All @@ -76,14 +71,11 @@ pub struct Hip {
pub mem_get_info: unsafe extern "C" fn(*mut usize, *mut usize) -> c_int,
pub malloc: unsafe extern "C" fn(*mut *mut c_void, usize) -> c_int,
pub free: unsafe extern "C" fn(*mut c_void) -> c_int,
pub memset: unsafe extern "C" fn(*mut c_void, c_int, usize) -> c_int,
pub memset_async: unsafe extern "C" fn(*mut c_void, c_int, usize, Stream) -> c_int,
pub memcpy: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int) -> c_int,
pub memcpy_async: unsafe extern "C" fn(*mut c_void, *const c_void, usize, c_int, Stream) -> c_int,
pub stream_create: unsafe extern "C" fn(*mut Stream, u32) -> c_int,
pub stream_destroy: unsafe extern "C" fn(Stream) -> c_int,
pub stream_sync: unsafe extern "C" fn(Stream) -> c_int,
pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> c_int,
pub stream_begin_capture: unsafe extern "C" fn(Stream, c_int) -> c_int,
pub stream_end_capture: unsafe extern "C" fn(Stream, *mut Graph) -> c_int,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability · 5 of 6

Removed FFI fields change the public Hip struct API and drop lifecycle calls. Hip has pub fields, so removing stream_destroy, module_unload, event_query and last_error breaks any downstream crate that uses them. Within this crate, nothing can now destroy a stream or unload a module through this struct, which leaves resource cleanup impossible if a later change needs it.

Prompt for your AI agent
File: src/hip/ffi.rs
Line: 81
Symbol: Hip
Issue: Removed FFI fields change the public Hip struct API and drop lifecycle calls. `Hip` has `pub` fields, so removing `stream_destroy`, `module_unload`, `event_query` and `last_error` breaks any downstream crate that uses them. Within this crate, nothing can now destroy a stream or unload a module through this struct, which leaves resource cleanup impossible if a later change needs it.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/dismiss ffi is a private module (mod ffi; in src/hip/mod.rs), so the pub fields of Hip are not reachable from any other crate or module outside hip. No downstream API changes. Within the crate nothing called stream_destroy, module_unload, event_query or last_error; if a later change adds the cleanup it can add the symbol lookup back.

pub stream_is_capturing: unsafe extern "C" fn(Stream, *mut c_int) -> c_int,
Expand All @@ -94,18 +86,15 @@ pub struct Hip {
pub event_create: unsafe extern "C" fn(*mut Event, u32) -> c_int,
pub event_record: unsafe extern "C" fn(Event, Stream) -> c_int,
pub event_sync: unsafe extern "C" fn(Event) -> c_int,
pub event_query: unsafe extern "C" fn(Event) -> c_int,
pub event_destroy: unsafe extern "C" fn(Event) -> c_int,
pub host_malloc: unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> c_int,
pub host_free: unsafe extern "C" fn(*mut c_void) -> c_int,
pub host_device_ptr: unsafe extern "C" fn(*mut *mut c_void, *mut c_void, u32) -> c_int,
pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> c_int,
pub module_unload: unsafe extern "C" fn(Module) -> c_int,
pub function: unsafe extern "C" fn(*mut Func, Module, *const c_char) -> c_int,
pub launch: unsafe extern "C" fn(Func, u32, u32, u32, u32, u32, u32, u32, Stream, *mut *mut c_void, *mut *mut c_void) -> c_int,
pub func_set_attribute: unsafe extern "C" fn(*const c_void, c_int, c_int) -> c_int,
pub error_string: unsafe extern "C" fn(c_int) -> *const c_char,
pub last_error: unsafe extern "C" fn() -> c_int,
_lib: Library,
}

Expand Down Expand Up @@ -142,14 +131,11 @@ impl Hip {
mem_get_info: g!("hipMemGetInfo"),
malloc: g!("hipMalloc"),
free: g!("hipFree"),
memset: g!("hipMemset"),
memset_async: g!("hipMemsetAsync"),
memcpy: g!("hipMemcpy"),
memcpy_async: g!("hipMemcpyAsync"),
stream_create: g!("hipStreamCreateWithFlags"),
stream_destroy: g!("hipStreamDestroy"),
stream_sync: g!("hipStreamSynchronize"),
stream_wait_event: g!("hipStreamWaitEvent"),
stream_begin_capture: g!("hipStreamBeginCapture"),
stream_end_capture: g!("hipStreamEndCapture"),
stream_is_capturing: g!("hipStreamIsCapturing"),
Expand All @@ -160,18 +146,15 @@ impl Hip {
event_create: g!("hipEventCreateWithFlags"),
event_record: g!("hipEventRecord"),
event_sync: g!("hipEventSynchronize"),
event_query: g!("hipEventQuery"),
event_destroy: g!("hipEventDestroy"),
host_malloc: g!("hipHostMalloc"),
host_free: g!("hipHostFree"),
host_device_ptr: g!("hipHostGetDevicePointer"),
module_load: g!("hipModuleLoadData"),
module_unload: g!("hipModuleUnload"),
function: g!("hipModuleGetFunction"),
launch: g!("hipModuleLaunchKernel"),
func_set_attribute: g!("hipFuncSetAttribute"),
error_string: g!("hipGetErrorString"),
last_error: g!("hipGetLastError"),
_lib: lib,
})
}
Expand Down
27 changes: 6 additions & 21 deletions src/hip/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ pub struct Gpu {
hip: Arc<ffi::Hip>,
device: usize,
stream: ffi::Stream,
module: ffi::Module,
fns: HashMap<String, ffi::Func>,
/// "gfx1201": the target hiprtc compiled for.
arch: String,
Expand All @@ -45,13 +44,8 @@ pub struct Gpu {
max_smem: usize,
/// `argmax_rows` partials.
am: Buf,
/// q8 rows of the last integer GEMM's X (see quant_q8 in kernels.cu) and which x they hold; `None` after a call
/// without `SAME_X` that did not quantize.
q8: Mutex<(Buf, Option<[u64; 4]>)>,
/// Recorded graphs by `Backend::graph` key.
graphs: Mutex<HashMap<u64, Graph>>,
/// Recorded by `sync`, so a wait can poll it instead of spinning in the driver.
done: ffi::Event,
/// Rope frequency tables, `base` and `n_rot` to the device buffer that holds them.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 3 of 6

The q8 cache is removed though its doc says live code uses it. The removed field doc says q8 rows of the last integer GEMM's X are cached and that SAME_X depends on it. If the GEMM path still checks or updates self.q8 anywhere, the crate does not compile. If the path instead recomputes the quantization, the cache-hit optimization is lost. Either way, the 'unused' premise conflicts with the removed comment.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 49
Symbol: Gpu
Issue: The q8 cache is removed though its doc says live code uses it. The removed field doc says q8 rows of the last integer GEMM's X are cached and that `SAME_X` depends on it. If the GEMM path still checks or updates `self.q8` anywhere, the crate does not compile. If the path instead recomputes the quantization, the cache-hit optimization is lost. Either way, the 'unused' premise conflicts with the removed comment.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/dismiss q8 was a Mutex<(Buf, Option<[u64; 4]>)> holding a 1-byte buffer, and nothing read or wrote it, so no SAME_X cache hit depended on it. The kernels keep their own q8 rows in the buffers they are given. If any code path used self.q8 the crate would not compile; it builds with no errors and the 11 hip tests pass.

fr: Mutex<(HashMap<(u32, usize), Buf>, Vec<(f32, usize)>)>,
/// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next
Expand Down Expand Up @@ -208,21 +202,16 @@ impl Gpu {
}
// argmax_part writes an int2 (8 bytes) per partial: AMAX_PARTS per row, up to 64 rows.
let am_buf = alloc_raw(&hip, 64 * AMAX_PARTS * 8)?;
let q8_buf = alloc_raw(&hip, 1)?;
// Pinned ring for large host-to-device copies.
let mut host: *mut c_void = std::ptr::null_mut();
hip.check(unsafe { (hip.host_malloc)(&mut host, RING, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc(ring)")?;
let mut dev: *mut c_void = std::ptr::null_mut();
hip.check(unsafe { (hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer(ring)")?;
let staging = Staging { pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() };
let mut done: ffi::Event = std::ptr::null_mut();
hip.check(unsafe { (hip.event_create)(&mut done, ffi::EVENT_DISABLE_TIMING) }, "hipEventCreate")?;
Ok(Gpu { hip, device, stream, module, fns, arch, kv_q8, max_smem, am: am_buf, q8: Mutex::new((q8_buf, None)),
graphs: Mutex::new(HashMap::new()), done, fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) })
let staging = Staging { _pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 1

Removing the module field drops the only record of the loaded module, and no unload path remains. Gpu::new loads a module, stores it in module, and the field is now removed. Nothing unloads it, and module_unload was also removed from ffi.rs, so every Gpu created in the process leaks its module (and the device code it holds) until exit. Creating and dropping Gpu instances repeatedly grows device memory use.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 210
Symbol: new
Issue: Removing the `module` field drops the only record of the loaded module, and no unload path remains. Gpu::new loads a module, stores it in `module`, and the field is now removed. Nothing unloads it, and `module_unload` was also removed from ffi.rs, so every Gpu created in the process leaks its module (and the device code it holds) until exit. Creating and dropping Gpu instances repeatedly grows device memory use.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Ok(Gpu { hip, device, stream, fns, arch, kv_q8, max_smem, am: am_buf,
graphs: Mutex::new(HashMap::new()), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) })
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 4 of 6

The module handle is no longer stored and is never unloaded. The module field is removed from Gpu and not kept anywhere, while hipModuleUnload was also removed from ffi. The loaded HIP module therefore cannot be released by this type. Any module local left in the constructor becomes unused, which trips unused_variables and fails builds that deny warnings.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 213
Symbol: new
Issue: The module handle is no longer stored and is never unloaded. The `module` field is removed from Gpu and not kept anywhere, while `hipModuleUnload` was also removed from ffi. The loaded HIP module therefore cannot be released by this type. Any `module` local left in the constructor becomes unused, which trips `unused_variables` and fails builds that deny warnings.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/dismiss The module local in Gpu::new is still used for the hipModuleGetFunction lookups, so there is no unused-variable warning. That the module is never unloaded was already true before this PR: nothing called hipModuleUnload, which is why the compiler flagged module_unload as unread. Adding a Drop for Gpu (stream, module, buffers, graphs) is a separate change, see my comment above.


fn h(&self) -> &ffi::Hip { &self.hip }

pub fn arch(&self) -> &str { &self.arch }

/// Launch kernel `name` with `cfg`; `args` are the kernel parameters, in order, read from the given addresses.
Expand All @@ -249,10 +238,6 @@ impl Gpu {

fn ptr(&self, b: &Buf) -> u64 { b.addr() }

fn f(&self, name: &str) -> anyhow::Result<ffi::Func> {
self.fns.get(name).copied().ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded"))
}

/// qwen35moe and the other models this backend targets dequantize in the kernel, so the ops below are the

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 6

Removing Gpu::h and Gpu::f breaks any caller that is not in this diff. The diff deletes fn h(&self) and fn f(&self, name) on Gpu, but only the struct and constructor are shown. If any kernel-launch or accessor code elsewhere in the crate still calls self.h() or self.f("..."), the crate fails to compile. The 'unused' claim is not verified in the diff.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 241
Issue: Removing Gpu::h and Gpu::f breaks any caller that is not in this diff. The diff deletes `fn h(&self)` and `fn f(&self, name)` on Gpu, but only the struct and constructor are shown. If any kernel-launch or accessor code elsewhere in the crate still calls `self.h()` or `self.f("...")`, the crate fails to compile. The 'unused' claim is not verified in the diff.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/dismiss Gpu::h and Gpu::f have no callers. The compiler reports them as never used, and it checks the whole crate, not only this diff. After removing them cargo build gives 0 warnings and 0 errors and the 11 hip tests pass on the RX 9070 XT. A caller anywhere in the crate would not compile.

/// generic ones.
fn float_ty(ty: GgmlType) -> bool { matches!(ty, GgmlType::F32 | GgmlType::BF16) }
Expand Down Expand Up @@ -405,13 +390,14 @@ impl Drop for PinnedHost {

/// Pinned host memory used as a ring for `htod`: a region is free again once the copy that read it has completed.
struct Staging {
pin: Buf,
/// Owns the pinned allocation; dropping it frees the ring.
_pin: Buf,
host: *mut u8,
head: usize,
busy: VecDeque<(usize, usize, Event)>,
}

/// A `hipEvent_t` that destroys itself; `query` reports completion.
/// A `hipEvent_t` that destroys itself.
struct Event { hip: Arc<ffi::Hip>, ev: ffi::Event }

impl Event {
Expand All @@ -423,7 +409,6 @@ impl Event {
fn record(&self, stream: ffi::Stream) -> anyhow::Result<()> {
self.hip.check(unsafe { (self.hip.event_record)(self.ev, stream) }, "hipEventRecord")
}
fn done(&self) -> bool { unsafe { (self.hip.event_query)(self.ev) == ffi::HIP_SUCCESS } }
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 6

Removing the event query path makes waits spin in the driver. The removed done field was documented as 'recorded by sync, so a wait can poll it instead of spinning in the driver', and Event::done used hipEventQuery. With both removed, any wait loop that depended on polling now blocks or busy-waits in the driver, costing CPU and latency. The change deletes a performance mechanism, not just dead code.

Prompt for your AI agent
File: src/hip/mod.rs
Line: 413
Issue: Removing the event query path makes waits spin in the driver. The removed `done` field was documented as 'recorded by sync, so a wait can poll it instead of spinning in the driver', and `Event::done` used `hipEventQuery`. With both removed, any wait loop that depended on polling now blocks or busy-waits in the driver, costing CPU and latency. The change deletes a performance mechanism, not just dead code.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/dismiss This does not remove a wait path. The done field was never recorded: on origin/main Backend::sync is self.wait(), which is hipStreamSynchronize, and nothing touches done. Its doc comment was stale. The waits that do use events (Event::new, record, hipEventSynchronize in the staging ring) are unchanged. Event::done and hipEventQuery had no caller, so no wait loop used them.

impl Drop for Event {
Expand Down
Loading