Skip to content

Commit

Permalink
Fix context aliveness in test and README
Browse files Browse the repository at this point in the history
  • Loading branch information
lukstafi committed Sep 29, 2024
1 parent d4d06bf commit 833b7e0
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ let prog = Cu.compile_to_ptx ~cu_src:kernel ~name:"saxpy" ~options:[ "--use_fast
let () =
Cu.init ();
let device = Cu.device_get ~ordinal:0 in
let _context = Cu.ctx_create ~flags:0 device in
let context = Cu.ctx_create ~flags:0 device in
let module_ = Cu.module_load_data_ex prog [] in
let kernel = Cu.module_get_function module_ ~name:"saxpy" in
...
Expand All @@ -34,12 +34,14 @@ let () =
Cu.memcpy_D_to_H ~dst:hOut ~src:dOut ();
Cu.mem_free dX;
...
Cu.module_unload module_
Cu.module_unload module_;
(* Keep the context alive up till here. *)
ignore (Sys.opaque_identity context)
```

(the `...` are parts omitted for presentation brevity).
You can see how a kernel is compiled and launched, how on-device tensors are created, retrieved to host
(i.e. the CPU), and released. `_context` is (or might be) destroyed when it is finalized by GC.
(i.e. the CPU), and released.

Note that you don't need to add the include path to the `compile_to_ptx` options.

Expand Down
4 changes: 3 additions & 1 deletion test/saxpy.ml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ let%expect_test "SAXPY" =
Cu.init ();
if Cu.Device.get_count () > 0 then (
let device = Cu.Device.get ~ordinal:0 in
let _context = Cu.Context.create [] device in
let context = Cu.Context.create [] device in
let module_ = Cu.Module.load_data_ex prog [] in
let kernel = Cu.Module.get_function module_ ~name:"saxpy" in
let size = num_threads * num_blocks in
Expand Down Expand Up @@ -55,6 +55,8 @@ let%expect_test "SAXPY" =
Cu.Deviceptr.mem_free dY;
Cu.Deviceptr.mem_free dOut;
Cu.Module.unload module_;
(* Keep the context around up till here. *)
ignore (Sys.opaque_identity context);
Format.set_margin 110;
for i = 0 to size - 1 do
let ( ! ) arr = Host.get arr [| i |] in
Expand Down

0 comments on commit 833b7e0

Please sign in to comment.