From d6c6821d9a69eda3568cbe71616cbc8e072f8d00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=B4=EC=9E=AC=EA=B7=A0?= Date: Wed, 14 Jan 2026 15:55:07 +0900 Subject: [PATCH 1/4] =?UTF-8?q?gemm=20=EC=8B=A4=ED=97=98=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=20f-string=20syntax=20=EC=98=A4=EB=A5=98=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- experiments/gemm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/experiments/gemm.py b/experiments/gemm.py index 3090e3312..b3e0342c8 100644 --- a/experiments/gemm.py +++ b/experiments/gemm.py @@ -31,7 +31,7 @@ def custom_matmul(a, b): import os import sys base_dir = os.environ.get('TORCHSIM_DIR', default='/workspace/PyTorchSim') - config = os.environ.get('TORCHSIM_CONFIG', default=f'{base_dir}/configs/systolic_ws_128x128_c2_simple_noc_tpuv4.yml) + config = os.environ.get('TORCHSIM_CONFIG', default=f'{base_dir}/configs/systolic_ws_128x128_c2_simple_noc_tpuv4.yml') config_prefix = config.split('/')[-1].split('.')[0][9:] # extract config name from config path sys.path.append(base_dir) args = argparse.ArgumentParser() From 62675e5d9f5f9108f0e0192bc4ecf699a4dbecb8 Mon Sep 17 00:00:00 2001 From: Wonhyuk Yang Date: Wed, 4 Feb 2026 04:32:40 +0000 Subject: [PATCH 2/4] [Scheduler] WIP (4) --- .../torch_openreg/csrc/Module.cpp | 179 +----------------- .../torch_openreg/openreg/__init__.py | 101 +++------- Simulator/simulator.py | 33 +--- tests/test_stream.py | 16 +- 4 files changed, 39 insertions(+), 290 deletions(-) diff --git a/PyTorchSimDevice/torch_openreg/csrc/Module.cpp b/PyTorchSimDevice/torch_openreg/csrc/Module.cpp index 31d0c6a81..d3ad5c0d1 100644 --- a/PyTorchSimDevice/torch_openreg/csrc/Module.cpp +++ b/PyTorchSimDevice/torch_openreg/csrc/Module.cpp @@ -185,171 +185,6 @@ PyObject* _streamDestroy(PyObject* self, PyObject* arg) { END_HANDLE_TH_ERRORS } -PyObject* _streamSynchronize(PyObject* self, PyObject* arg) { - HANDLE_TH_ERRORS - TORCH_CHECK(THPUtils_checkLong(arg), "stream_synchronize expects an int"); - orStream_t stream = reinterpret_cast(THPUtils_unpackLong(arg)); - - orError_t err; - Py_BEGIN_ALLOW_THREADS - err = orStreamSynchronize(stream); - Py_END_ALLOW_THREADS - - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to synchronize stream"); - } - Py_RETURN_NONE; - END_HANDLE_TH_ERRORS -} - -PyObject* _streamQuery(PyObject* self, PyObject* arg) { - HANDLE_TH_ERRORS - TORCH_CHECK(THPUtils_checkLong(arg), "stream_query expects an int"); - orStream_t stream = reinterpret_cast(THPUtils_unpackLong(arg)); - orError_t err = orStreamQuery(stream); - if (err == orSuccess) { - Py_RETURN_TRUE; - } else { - Py_RETURN_FALSE; - } - END_HANDLE_TH_ERRORS -} - -PyObject* _streamGetPriority(PyObject* self, PyObject* arg) { - HANDLE_TH_ERRORS - TORCH_CHECK(THPUtils_checkLong(arg), "stream_get_priority expects an int"); - orStream_t stream = reinterpret_cast(THPUtils_unpackLong(arg)); - int priority = 0; - orError_t err = orStreamGetPriority(stream, &priority); - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to get stream priority"); - } - return THPUtils_packInt32(priority); - END_HANDLE_TH_ERRORS -} - -PyObject* _streamWaitEvent(PyObject* self, PyObject* args) { - HANDLE_TH_ERRORS - TORCH_CHECK(PyTuple_Size(args) == 2, "stream_wait_event expects 2 arguments"); - PyObject* stream_obj = PyTuple_GetItem(args, 0); - PyObject* event_obj = PyTuple_GetItem(args, 1); - TORCH_CHECK(THPUtils_checkLong(stream_obj), "stream must be an int"); - TORCH_CHECK(THPUtils_checkLong(event_obj), "event must be an int"); - orStream_t stream = reinterpret_cast(THPUtils_unpackLong(stream_obj)); - orEvent_t event = reinterpret_cast(THPUtils_unpackLong(event_obj)); - orError_t err = orStreamWaitEvent(stream, event, 0); - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to wait for event"); - } - Py_RETURN_NONE; - END_HANDLE_TH_ERRORS -} - -// Event functions -PyObject* _eventCreate(PyObject* self, PyObject* noargs) { - HANDLE_TH_ERRORS - torch::utils::device_lazy_init(at::kPrivateUse1); - orEvent_t event = nullptr; - orError_t err = orEventCreate(&event); - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to create event"); - } - return THPUtils_packInt64(reinterpret_cast(event)); - END_HANDLE_TH_ERRORS -} - -PyObject* _eventCreateWithFlags(PyObject* self, PyObject* arg) { - HANDLE_TH_ERRORS - TORCH_CHECK(THPUtils_checkLong(arg), "event_create_with_flags expects an int"); - unsigned int flags = static_cast(THPUtils_unpackLong(arg)); - - torch::utils::device_lazy_init(at::kPrivateUse1); - orEvent_t event = nullptr; - orError_t err = orEventCreateWithFlags(&event, flags); - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to create event with flags"); - } - return THPUtils_packInt64(reinterpret_cast(event)); - END_HANDLE_TH_ERRORS -} - -PyObject* _eventDestroy(PyObject* self, PyObject* arg) { - HANDLE_TH_ERRORS - TORCH_CHECK(THPUtils_checkLong(arg), "event_destroy expects an int"); - orEvent_t event = reinterpret_cast(THPUtils_unpackLong(arg)); - orError_t err = orEventDestroy(event); - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to destroy event"); - } - Py_RETURN_NONE; - END_HANDLE_TH_ERRORS -} - -PyObject* _eventRecord(PyObject* self, PyObject* args) { - HANDLE_TH_ERRORS - TORCH_CHECK(PyTuple_Size(args) == 2, "event_record expects 2 arguments"); - PyObject* event_obj = PyTuple_GetItem(args, 0); - PyObject* stream_obj = PyTuple_GetItem(args, 1); - TORCH_CHECK(THPUtils_checkLong(event_obj), "event must be an int"); - TORCH_CHECK(THPUtils_checkLong(stream_obj), "stream must be an int"); - orEvent_t event = reinterpret_cast(THPUtils_unpackLong(event_obj)); - orStream_t stream = reinterpret_cast(THPUtils_unpackLong(stream_obj)); - orError_t err = orEventRecord(event, stream); - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to record event"); - } - Py_RETURN_NONE; - END_HANDLE_TH_ERRORS -} - -PyObject* _eventSynchronize(PyObject* self, PyObject* arg) { - HANDLE_TH_ERRORS - TORCH_CHECK(THPUtils_checkLong(arg), "event_synchronize expects an int"); - orEvent_t event = reinterpret_cast(THPUtils_unpackLong(arg)); - - orError_t err; - Py_BEGIN_ALLOW_THREADS - err = orEventSynchronize(event); - Py_END_ALLOW_THREADS - - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to synchronize event"); - } - Py_RETURN_NONE; - END_HANDLE_TH_ERRORS -} - -PyObject* _eventQuery(PyObject* self, PyObject* arg) { - HANDLE_TH_ERRORS - TORCH_CHECK(THPUtils_checkLong(arg), "event_query expects an int"); - orEvent_t event = reinterpret_cast(THPUtils_unpackLong(arg)); - orError_t err = orEventQuery(event); - if (err == orSuccess) { - Py_RETURN_TRUE; - } else { - Py_RETURN_FALSE; - } - END_HANDLE_TH_ERRORS -} - -PyObject* _eventElapsedTime(PyObject* self, PyObject* args) { - HANDLE_TH_ERRORS - TORCH_CHECK(PyTuple_Size(args) == 2, "event_elapsed_time expects 2 arguments"); - PyObject* start_obj = PyTuple_GetItem(args, 0); - PyObject* end_obj = PyTuple_GetItem(args, 1); - TORCH_CHECK(THPUtils_checkLong(start_obj), "start event must be an int"); - TORCH_CHECK(THPUtils_checkLong(end_obj), "end event must be an int"); - orEvent_t start = reinterpret_cast(THPUtils_unpackLong(start_obj)); - orEvent_t end = reinterpret_cast(THPUtils_unpackLong(end_obj)); - float ms = 0.0f; - orError_t err = orEventElapsedTime(&ms, start, end); - if (err != orSuccess) { - TORCH_CHECK(false, "Failed to get elapsed time"); - } - return PyFloat_FromDouble(static_cast(ms)); - END_HANDLE_TH_ERRORS -} - PyObject* _deviceSynchronize(PyObject* self, PyObject* noargs) { HANDLE_TH_ERRORS torch::utils::device_lazy_init(at::kPrivateUse1); @@ -421,20 +256,8 @@ static PyMethodDef methods[] = { {"get_amp_supported_dtype", _getAmpSupportedDtype, METH_NOARGS, nullptr}, // Stream functions {"_stream_create", _streamCreate, METH_NOARGS, nullptr}, - {"_stream_create_with_priority", _streamCreateWithPriority, METH_VARARGS, nullptr}, {"_stream_destroy", _streamDestroy, METH_O, nullptr}, - {"_stream_synchronize", _streamSynchronize, METH_O, nullptr}, - {"_stream_query", _streamQuery, METH_O, nullptr}, - {"_stream_get_priority", _streamGetPriority, METH_O, nullptr}, - {"_stream_wait_event", _streamWaitEvent, METH_VARARGS, nullptr}, - // Event functions - {"_event_create", _eventCreate, METH_NOARGS, nullptr}, - {"_event_create_with_flags", _eventCreateWithFlags, METH_O, nullptr}, - {"_event_destroy", _eventDestroy, METH_O, nullptr}, - {"_event_record", _eventRecord, METH_VARARGS, nullptr}, - {"_event_synchronize", _eventSynchronize, METH_O, nullptr}, - {"_event_query", _eventQuery, METH_O, nullptr}, - {"_event_elapsed_time", _eventElapsedTime, METH_VARARGS, nullptr}, + // Device functions {"_device_synchronize", _deviceSynchronize, METH_NOARGS, nullptr}, // Stream task functions diff --git a/PyTorchSimDevice/torch_openreg/openreg/__init__.py b/PyTorchSimDevice/torch_openreg/openreg/__init__.py index b7d28291b..b34047b7e 100644 --- a/PyTorchSimDevice/torch_openreg/openreg/__init__.py +++ b/PyTorchSimDevice/torch_openreg/openreg/__init__.py @@ -8,6 +8,7 @@ from .extension_device_interface import ExtensionDeviceInterface _initialized = False +_default_streams = {} # Dictionary to store default streams per device class device: @@ -64,36 +65,21 @@ def _lazy_init(): register_interface_for_device(custom_device(), ExtensionDeviceInterface) _initialized = True + # Create default streams for all devices + num_devices = device_count() + for device_idx in range(num_devices): + _default_streams[device_idx] = Stream() class Stream: """Wrapper for OpenReg stream.""" - def __init__(self, priority=None, flags=0): - if priority is not None: - self._stream = torch_openreg._C._stream_create_with_priority(flags, priority) - else: - self._stream = torch_openreg._C._stream_create() + def __init__(self, flags=0): + self._stream = torch_openreg._C._stream_create() def __del__(self): if hasattr(self, '_stream'): torch_openreg._C._stream_destroy(self._stream) - def synchronize(self): - """Wait for all operations in the stream to complete.""" - torch_openreg._C._stream_synchronize(self._stream) - - def query(self): - """Check if all operations in the stream have completed.""" - return torch_openreg._C._stream_query(self._stream) - - def wait_event(self, event): - """Make this stream wait for an event.""" - torch_openreg._C._stream_wait_event(self._stream, event._event) - - def get_priority(self): - """Get the priority of the stream.""" - return torch_openreg._C._stream_get_priority(self._stream) - def launch_kernel(self, task): """Add a Python callable kernel to this stream. @@ -108,74 +94,43 @@ def cdata(self): return self._stream -class Event: - """Wrapper for OpenReg event.""" - - def __init__(self, enable_timing=False): - if enable_timing: - # orEventEnableTiming = 0x1 - self._event = torch_openreg._C._event_create_with_flags(0x1) - else: - self._event = torch_openreg._C._event_create() - - def __del__(self): - if hasattr(self, '_event'): - torch_openreg._C._event_destroy(self._event) - - def record(self, stream=None): - """Record the event in a stream.""" - if stream is None: - # Use default stream (stream 0) - stream = Stream() - torch_openreg._C._event_record(self._event, stream._stream) - - def synchronize(self): - """Wait for the event to complete.""" - torch_openreg._C._event_synchronize(self._event) - - def query(self): - """Check if the event has completed.""" - return torch_openreg._C._event_query(self._event) - - def elapsed_time(self, start_event): - """Get the elapsed time between two events in milliseconds.""" - return torch_openreg._C._event_elapsed_time(start_event._event, self._event) - - @property - def cdata(self): - """Get the underlying event pointer (for internal use).""" - return self._event - - def synchronize(): """Synchronize all streams on the current device.""" torch_openreg._C._device_synchronize() -def stream(priority=None, flags=0): +def stream(flags=0): """Create a new stream. Args: - priority: Stream priority (optional) flags: Stream flags (optional) Returns: Stream: A new stream object """ - return Stream(priority=priority, flags=flags) + return Stream(flags=flags) +def default_stream(device=None): + _lazy_init() + if device is None: + device_idx = current_device() + else: + device_idx = torch.accelerator._get_device_index(device, optional=True) + if device_idx < 0: + device_idx = current_device() -def event(enable_timing=False): - """Create a new event. + if device_idx not in _default_streams: + # Create default stream if it doesn't exist + _default_streams[device_idx] = Stream() - Args: - enable_timing: Whether to enable timing for the event + return _default_streams[device_idx] - Returns: - Event: A new event object - """ - return Event(enable_timing=enable_timing) +def launch_kernel(task, stream=None): + _lazy_init() + if stream is None: + stream = default_stream() + stream.launch_kernel(task) from .random import * # noqa: F403 from .amp import * @@ -200,9 +155,7 @@ def event(enable_timing=False): "get_autocast_dtype", "set_autocast_dtype", "get_amp_supported_dtype", - "Stream", - "Event", "stream", - "event", + "launch_kernel", "synchronize", ] diff --git a/Simulator/simulator.py b/Simulator/simulator.py index d134f3820..4b76a640f 100644 --- a/Simulator/simulator.py +++ b/Simulator/simulator.py @@ -246,7 +246,7 @@ def __init__(self, togsim_path, config_path, vectorlane_size=-1) -> None: os.mkfifo(self.trace_file_path) os.mkfifo(self.event_fifo_path) - # Start TOGSim process with FIFO mode + # Start TOGSim process self._start_process() # Open trace file FIFO once and keep it open (after process starts) @@ -382,7 +382,7 @@ def launch_kernel(self, device_index, stream_index, tog_path, attribute_path): # Format command: id,device_index,stream_index,tog_path,attribute_path command = f"{kernel_id},{device_index},{stream_index},{tog_path},{attribute_path}" - + with self._trace_file_lock: # Write command to FIFO try: @@ -445,23 +445,6 @@ def get_core_freq(self): else: raise KeyError("Key 'core_freq' not found in JSON.") - def find_zero_sub_tensors(self, tensor): - x, y = self.vectorlane_size, self.vectorlane_size - zero_positions = {} - - # Need to set vectorlane size - if self.vectorlane_size == -1: - return zero_positions - - for i in range(0, tensor.shape[0], y): - for j in range(0, tensor.shape[1], x): - sub_tensor = tensor[i:i + y, j:j + x] - if np.all(sub_tensor == 0): - if i not in zero_positions: - zero_positions[i] = {} - zero_positions[i][j] = 0 # i pos : j pos : 0 - return zero_positions - @staticmethod def get_result_from_file(result_path): core_metrics = {} @@ -524,27 +507,27 @@ def get_result_from_file(result_path): if __name__ == "__main__": sim = TOGSimulator("/workspace/PyTorchSim/TOGSim", "/workspace/PyTorchSim/configs/systolic_ws_128x128_c2_simple_noc_tpuv3_partition.yml", 128) - + # Test: Launch multiple kernels try: # Example paths (adjust these to your actual test files) test_tog_path = "/workspace/PyTorchSim/outputs/6vxl6mwzhfl/tile_graph.onnx" test_attribute_path = "/workspace/PyTorchSim/outputs/6vxl6mwzhfl/runtime_0001/attribute/0" - + print("Launching kernel 1...") id1 = sim.launch_kernel(device_index=0, stream_index=0, tog_path=test_tog_path, attribute_path=test_attribute_path) print(f"Kernel 1 launched with ID: {id1}") - + print("Launching kernel 2...") id2 = sim.launch_kernel(device_index=0, stream_index=0, tog_path=test_tog_path, attribute_path=test_attribute_path) print(f"Kernel 2 launched with ID: {id2}") - + print("Launching kernel 3...") id3 = sim.launch_kernel(device_index=0, stream_index=0, tog_path=test_tog_path, attribute_path=test_attribute_path) print(f"Kernel 3 launched with ID: {id3}") - + print("All kernels launched successfully!") - + except Exception as e: print(f"Error during kernel launch: {e}") finally: diff --git a/tests/test_stream.py b/tests/test_stream.py index 70077abec..70b2c34b2 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -1,22 +1,12 @@ import torch import time -start_event = torch.npu.event(enable_timing=True) -end_event = torch.npu.event(enable_timing=True) -stream = torch.npu.stream() - def my_kernel(): print("Task is running...") result = sum(range(1000)) time.sleep(2.5) print(f"Task completed with result: {result}") -start_event.record(stream) -stream.launch_kernel(my_kernel) -end_event.record(stream) - - -stream.synchronize() - -elapsed_time = end_event.elapsed_time(start_event) -print("Event has completed! ", elapsed_time) \ No newline at end of file +torch.npu.launch_kernel(my_kernel) +torch.npu.synchronize() +print("Task completed!") \ No newline at end of file From baae141af0ab1936883cd3ef4e2f7f55b4cb5f68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=B4=EC=9E=AC=EA=B7=A0?= Date: Wed, 4 Feb 2026 14:18:41 +0900 Subject: [PATCH 3/4] [Scheduler] TOGSim Daemonization from dummy_simulator (WIP) --- PyTorchSimFrontend/extension_codecache.py | 51 +++++++++++++++++++---- 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/PyTorchSimFrontend/extension_codecache.py b/PyTorchSimFrontend/extension_codecache.py index 5066d214b..32ff7edba 100644 --- a/PyTorchSimFrontend/extension_codecache.py +++ b/PyTorchSimFrontend/extension_codecache.py @@ -2,6 +2,7 @@ import re import shlex import subprocess +import threading from torch._inductor.codecache import get_lock_dir, get_hash, write from torch._inductor.async_compile import AsyncCompile @@ -14,6 +15,8 @@ logger = extension_config.setup_logger() LOCK_TIMEOUT = 600 +_TOGSIM_SINGLETON = None +_TOGSIM_LOCK = threading.Lock() def hash_prefix(hash_value): return hash_value[1:12] @@ -31,6 +34,24 @@ def dump_metadata(args, arg_attributes, path): file.write(f'{arg_name}=({arg_attribute[0]}, {arg.dtype}, {arg.shape})\n') return +def init_togsim(vectorlane_size=-1): + return get_togsim(vectorlane_size=vectorlane_size) + +def get_togsim(vectorlane_size=-1): + global _TOGSIM_SINGLETON + with _TOGSIM_LOCK: + if _TOGSIM_SINGLETON is not None: + proc = getattr(_TOGSIM_SINGLETON, "process", None) + if proc is not None and proc.poll() is None: + if vectorlane_size != -1: + _TOGSIM_SINGLETON.vectorlane_size = vectorlane_size + return _TOGSIM_SINGLETON + togsim_path = os.path.join(extension_config.CONFIG_TORCHSIM_DIR, "TOGSim") + _TOGSIM_SINGLETON = TOGSimulator(togsim_path, extension_config.CONFIG_TOGSIM_CONFIG) + if vectorlane_size != -1: + _TOGSIM_SINGLETON.vectorlane_size = vectorlane_size + return _TOGSIM_SINGLETON + def mlir_compile_command(filename, vectorlane_size, vlen=256): return [re.sub(r"[ \n]+", " ", f""" @@ -249,7 +270,7 @@ def __init__(self): def mlir(self, source_code, arg_attributes=[], vectorlane_size=16, tile_size=[], spad_info=None, origins=None, silent_mode=False, **kwargs): def task(): key = MLIRCodeCache.load(source_code, - valdiation_wrapper_name=self.validation_binary_name, + validation_wrapper_name=self.validation_wrapper_name, validation_binary_name=self.validation_binary_name, arg_attributes=arg_attributes, vectorlane_size=vectorlane_size, tile_size=tile_size, spad_info=spad_info, origins=origins, @@ -288,13 +309,29 @@ def dummy_simulator(*args, **kwargs): onnx_path = os.path.join(result_path, "tile_graph.onnx") attribute_path = os.path.join(runtime_path, "attribute") - togsim_path = os.path.join(extension_config.CONFIG_TORCHSIM_DIR, "TOGSim") - TOGSim = TOGSimulator(togsim_path, extension_config.CONFIG_TOGSIM_CONFIG) - TOGSim.vectorlane_size = vectorlane_size + + TOGSim = get_togsim(vectorlane_size=vectorlane_size) attribute_path = TOGSim.create_attribute_file(attribute_path, args, loop_size=loop_size) - result_path = TOGSim.simulation(onnx_path, attribute_path, silent_mode=silent_mode, autotune_mode=autotune) - result = TOGSimulator.get_result_from_file(result_path) - return result + + stream = kwargs.get("stream") + stream_index = 0 + if isinstance(stream, int): + stream_index = stream + + def _run_togsim_launch(): + TOGSim.launch_kernel( + device_index=0, + stream_index=stream_index, + tog_path=onnx_path, + attribute_path=attribute_path, + ) + + if stream is not None and hasattr(stream, "launch_kernel"): + stream.launch_kernel(_run_togsim_launch) + else: + _run_togsim_launch() + + return None def dryrun_simulator(*args, **kwargs): key = future.result() From 66c49066f6ae37cada9f193a144d5f8d5ecfd49c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=B4=EC=9E=AC=EA=B7=A0?= Date: Wed, 4 Feb 2026 16:28:27 +0900 Subject: [PATCH 4/4] [Scheduler] Stream globalization from extension_codecache (WIP) --- PyTorchSimFrontend/extension_codecache.py | 37 +++++++++++++++++++++-- tests/test_stream.py | 33 ++++++++++++++++---- 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/PyTorchSimFrontend/extension_codecache.py b/PyTorchSimFrontend/extension_codecache.py index 32ff7edba..065a2a4dc 100644 --- a/PyTorchSimFrontend/extension_codecache.py +++ b/PyTorchSimFrontend/extension_codecache.py @@ -17,6 +17,10 @@ LOCK_TIMEOUT = 600 _TOGSIM_SINGLETON = None _TOGSIM_LOCK = threading.Lock() +_STREAM_LOCK = threading.Lock() +_GLOBAL_STREAM = None +_STREAM_INDEX_MAP = {} +_NEXT_STREAM_INDEX = 1 def hash_prefix(hash_value): return hash_value[1:12] @@ -52,6 +56,33 @@ def get_togsim(vectorlane_size=-1): _TOGSIM_SINGLETON.vectorlane_size = vectorlane_size return _TOGSIM_SINGLETON +def set_current_stream(stream): + global _GLOBAL_STREAM + with _STREAM_LOCK: + _GLOBAL_STREAM = stream + +def get_current_stream(): + with _STREAM_LOCK: + return _GLOBAL_STREAM + +def get_stream_index(stream): + global _NEXT_STREAM_INDEX + if stream is None: + return 0 + if isinstance(stream, int): + return stream + + stream_key = getattr(stream, "cdata", None) + if stream_key is None: + stream_key = id(stream) + + with _STREAM_LOCK: + if stream_key not in _STREAM_INDEX_MAP: + _STREAM_INDEX_MAP[stream_key] = _NEXT_STREAM_INDEX + _NEXT_STREAM_INDEX += 1 + return _STREAM_INDEX_MAP[stream_key] + + def mlir_compile_command(filename, vectorlane_size, vlen=256): return [re.sub(r"[ \n]+", " ", f""" @@ -314,9 +345,9 @@ def dummy_simulator(*args, **kwargs): attribute_path = TOGSim.create_attribute_file(attribute_path, args, loop_size=loop_size) stream = kwargs.get("stream") - stream_index = 0 - if isinstance(stream, int): - stream_index = stream + if stream is None: + stream = get_current_stream() + stream_index = get_stream_index(stream) def _run_togsim_launch(): TOGSim.launch_kernel( diff --git a/tests/test_stream.py b/tests/test_stream.py index 70b2c34b2..559439513 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -1,12 +1,33 @@ import torch import time +from PyTorchSimFrontend.extension_codecache import ( + set_current_stream, + get_current_stream, + get_stream_index, +) -def my_kernel(): - print("Task is running...") + +def my_kernel(tag): + print(f"[{tag}] task is running...") result = sum(range(1000)) - time.sleep(2.5) - print(f"Task completed with result: {result}") + time.sleep(0.2) + print(f"[{tag}] task completed with result: {result}") + +# Create two streams and register one as global stream for dummy_simulator fallback +stream0 = torch.npu.Stream() +stream1 = torch.npu.Stream() +set_current_stream(stream0) + +print("Global stream is stream0:", get_current_stream() is stream0) +print("stream0 index:", get_stream_index(stream0)) +print("stream1 index:", get_stream_index(stream1)) +print("global stream index:", get_stream_index(get_current_stream())) + +# Queue tasks on each stream +stream0.launch_kernel(lambda: my_kernel("stream0")) +stream1.launch_kernel(lambda: my_kernel("stream1")) -torch.npu.launch_kernel(my_kernel) +# Default API path (uses NPU default stream) +torch.npu.launch_kernel(lambda: my_kernel("default_stream")) torch.npu.synchronize() -print("Task completed!") \ No newline at end of file +print("All stream tasks completed!")