1use std::{marker::PhantomData, sync::Arc};
2
3use cubecl::prelude::*;
4use cubecl_core::{self as cubecl, intrinsic, ir::Scope, unexpanded};
5
6use crate::tensor::layout::{Coordinates, Layout, LayoutExpand};
7
8#[derive(Clone)]
11pub struct VirtualLayout<C: Coordinates, S: Coordinates> {
12 _coords: PhantomData<(C, S)>,
13}
14
15impl<C: Coordinates, S: Coordinates> Copy for VirtualLayout<C, S> {}
16unsafe impl<C: Coordinates, S: Coordinates> Send for VirtualLayout<C, S> {}
17unsafe impl<C: Coordinates, S: Coordinates> Sync for VirtualLayout<C, S> {}
18
19#[derive(Clone)]
20pub struct VirtualLayoutExpand<C: Coordinates, S: Coordinates> {
21 pub(crate) state: Arc<dyn VirtualLayoutOperationsExpand<C, S>>,
22}
23
24#[cube]
25impl<C: Coordinates, S: Coordinates> VirtualLayout<C, S> {
26 #[allow(unused)]
28 pub fn to_source_pos(&self, pos: C) -> S {
29 intrinsic!(|scope| { self.state.__expand_to_source_pos_method(scope, pos) })
30 }
31
32 #[allow(unused)]
34 pub fn to_source_pos_checked(&self, pos: C) -> (S, bool) {
35 intrinsic!(|scope| { self.state.__expand_to_source_pos_checked_method(scope, pos) })
36 }
37
38 pub fn shape(&self) -> C {
40 intrinsic!(|scope| { self.state.__expand_shape_method(scope) })
41 }
42
43 #[allow(unused)]
45 pub fn is_in_bounds(&self, pos: C) -> bool {
46 intrinsic!(|scope| { self.state.__expand_is_in_bounds_method(scope, pos) })
47 }
48}
49
50impl<C: Coordinates, S: Coordinates> VirtualLayout<C, S> {
51 pub fn new<L: Layout<Coordinates = C, SourceCoordinates = S>>(
53 _layout: L,
54 ) -> VirtualLayout<C, S> {
55 unexpanded!()
56 }
57
58 pub fn __expand_new<L: Layout<Coordinates = C, SourceCoordinates = S> + 'static>(
60 _scope: &mut Scope,
61 layout: L::ExpandType,
62 ) -> VirtualLayoutExpand<C, S> {
63 VirtualLayoutExpand::new::<L::ExpandType>(layout)
64 }
65}
66
67impl<C: Coordinates, S: Coordinates> VirtualLayoutExpand<C, S> {
68 pub fn new<L: VirtualLayoutOperationsExpand<C, S> + 'static>(
70 layout: L,
71 ) -> VirtualLayoutExpand<C, S> {
72 VirtualLayoutExpand::<C, S> {
73 state: Arc::new(layout),
74 }
75 }
76}
77
78impl<C: Coordinates, S: Coordinates> CubeType for VirtualLayout<C, S> {
79 type ExpandType = VirtualLayoutExpand<C, S>;
80}
81
82impl<C: Coordinates, S: Coordinates> IntoMut for VirtualLayoutExpand<C, S> {
83 fn into_mut(self, _scope: &mut Scope) -> Self {
84 self
85 }
86}
87
88impl<C: Coordinates, S: Coordinates> CubeDebug for VirtualLayoutExpand<C, S> {}
89
90mod private {
92 pub trait Sealed {}
93}
94pub trait VirtualLayoutOperationsExpand<C: CubeType, S: CubeType>: private::Sealed {
95 fn __expand_to_source_pos_method(
96 &self,
97 scope: &mut Scope,
98 pos: <C as CubeType>::ExpandType,
99 ) -> <S as CubeType>::ExpandType;
100 fn __expand_to_source_pos_checked_method(
101 &self,
102 scope: &mut Scope,
103 pos: <C as CubeType>::ExpandType,
104 ) -> <(S, bool) as CubeType>::ExpandType;
105 fn __expand_shape_method(&self, scope: &mut Scope) -> <C as CubeType>::ExpandType;
106 fn __expand_is_in_bounds_method(
107 &self,
108 scope: &mut Scope,
109 pos: <C as CubeType>::ExpandType,
110 ) -> NativeExpand<bool>;
111}
112
113impl<L: LayoutExpand> private::Sealed for L {}
114impl<L: LayoutExpand> VirtualLayoutOperationsExpand<L::Coordinates, L::SourceCoordinates> for L {
115 fn __expand_to_source_pos_method(
116 &self,
117 scope: &mut Scope,
118 pos: <L::Coordinates as CubeType>::ExpandType,
119 ) -> <L::SourceCoordinates as CubeType>::ExpandType {
120 <L as LayoutExpand>::__expand_to_source_pos_method(self.clone(), scope, pos)
121 }
122
123 fn __expand_to_source_pos_checked_method(
124 &self,
125 scope: &mut Scope,
126 pos: <L::Coordinates as CubeType>::ExpandType,
127 ) -> <(L::SourceCoordinates, bool) as CubeType>::ExpandType {
128 <L as LayoutExpand>::__expand_to_source_pos_checked_method(self.clone(), scope, pos)
129 }
130
131 fn __expand_shape_method(&self, scope: &mut Scope) -> <L::Coordinates as CubeType>::ExpandType {
132 <L as LayoutExpand>::__expand_shape_method(self.clone(), scope)
133 }
134
135 fn __expand_is_in_bounds_method(
136 &self,
137 scope: &mut Scope,
138 pos: <L::Coordinates as CubeType>::ExpandType,
139 ) -> NativeExpand<bool> {
140 <L as LayoutExpand>::__expand_is_in_bounds_method(self.clone(), scope, pos)
141 }
142}
143
144impl<C: Coordinates, S: Coordinates, L: VirtualLayoutOperationsExpand<C, S> + 'static> From<L>
145 for VirtualLayoutExpand<C, S>
146{
147 fn from(value: L) -> Self {
148 VirtualLayoutExpand::new(value)
149 }
150}
151
152impl<L: Layout + 'static> From<L> for VirtualLayout<L::Coordinates, L::SourceCoordinates> {
153 fn from(_value: L) -> Self {
154 VirtualLayout {
155 _coords: PhantomData,
156 }
157 }
158}
159
160mod launch {
161 use alloc::rc::Rc;
162 use core::cell::RefCell;
163
164 use cubecl_core::{
165 format::DebugRaw,
166 hash::{StableHash, StableHasher},
167 };
168
169 use super::*;
170
171 type ExpandFn<C, S> =
172 Rc<RefCell<dyn FnMut(&mut KernelBuilder, bool) -> VirtualLayoutExpand<C, S> + Send>>;
173
174 pub struct VirtualLayoutLaunch<C: Coordinates, S: Coordinates, R: Runtime> {
175 _phantom_runtime: core::marker::PhantomData<R>,
176 #[allow(clippy::type_complexity)]
177 register: Box<
178 dyn FnOnce(&mut KernelLauncher<R>) -> VirtualLayoutCompilationArg<C, S> + Send + Sync,
179 >,
180 }
181
182 impl<C: Coordinates, S: Coordinates, R: Runtime> VirtualLayoutLaunch<C, S, R> {
183 pub fn new<L: Layout<Coordinates = C, SourceCoordinates = S> + LaunchArg>(
184 layout: L::RuntimeArg<R>,
185 ) -> Self {
186 Self {
187 _phantom_runtime: PhantomData,
188 register: Box::new(move |launcher| {
189 let comp_arg = L::register(layout, launcher);
190 let comp_arg_2 = comp_arg.clone();
191 let expand = move |builder: &mut KernelBuilder, is_out: bool| {
192 let expand = match is_out {
193 true => L::expand_output(&comp_arg_2, builder),
194 false => L::expand(&comp_arg_2, builder),
195 };
196 VirtualLayoutExpand::new(expand)
197 };
198 VirtualLayoutCompilationArg::new::<L::CompilationArg>(
199 comp_arg,
200 Rc::new(RefCell::new(expand)),
201 )
202 }),
203 }
204 }
205 }
206
207 #[derive(Clone)]
208 pub struct VirtualLayoutCompilationArg<C: Coordinates, S: Coordinates> {
209 type_name: String,
210 debug: Rc<dyn core::fmt::Debug>,
211 hash: StableHash,
212 expand: ExpandFn<C, S>,
213 }
214
215 unsafe impl<C: Coordinates, S: Coordinates> Send for VirtualLayoutCompilationArg<C, S> {}
217 unsafe impl<C: Coordinates, S: Coordinates> Sync for VirtualLayoutCompilationArg<C, S> {}
218
219 impl<C: Coordinates, S: Coordinates> VirtualLayoutCompilationArg<C, S> {
220 pub fn new<L: CompilationArg + 'static>(arg: L, expand: ExpandFn<C, S>) -> Self {
221 let hash = StableHasher::hash_one(&arg);
224 Self {
225 type_name: core::any::type_name::<L>().to_string(),
226 debug: Rc::new(arg),
227 hash,
228 expand,
229 }
230 }
231 }
232
233 impl<C: Coordinates, S: Coordinates> PartialEq for VirtualLayoutCompilationArg<C, S> {
234 fn eq(&self, other: &Self) -> bool {
235 self.type_name == other.type_name && self.hash == other.hash
236 }
237 }
238 impl<C: Coordinates, S: Coordinates> Eq for VirtualLayoutCompilationArg<C, S> {}
239
240 impl<C: Coordinates, S: Coordinates> core::hash::Hash for VirtualLayoutCompilationArg<C, S> {
241 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
242 self.type_name.hash(state);
243 self.hash.hash(state);
244 }
245 }
246
247 impl<C: Coordinates, S: Coordinates> core::fmt::Debug for VirtualLayoutCompilationArg<C, S> {
248 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249 f.debug_struct(stringify!(VirtualLayout))
250 .field("type", &DebugRaw(&self.type_name))
251 .field("value", &self.debug)
252 .finish()
253 }
254 }
255
256 impl<C: Coordinates + 'static, S: Coordinates + 'static> LaunchArg for VirtualLayout<C, S> {
257 type RuntimeArg<R: Runtime> = VirtualLayoutLaunch<C, S, R>;
258 type CompilationArg = VirtualLayoutCompilationArg<C, S>;
259
260 fn register<R: Runtime>(
261 arg: Self::RuntimeArg<R>,
262 launcher: &mut KernelLauncher<R>,
263 ) -> Self::CompilationArg {
264 let func = arg.register;
265 func(launcher)
266 }
267 fn expand(
268 arg: &Self::CompilationArg,
269 builder: &mut KernelBuilder,
270 ) -> <Self as CubeType>::ExpandType {
271 let mut expand = arg.expand.borrow_mut();
272 expand(builder, false)
273 }
274 fn expand_output(
275 arg: &Self::CompilationArg,
276 builder: &mut KernelBuilder,
277 ) -> <Self as CubeType>::ExpandType {
278 let mut expand = arg.expand.borrow_mut();
279 expand(builder, true)
280 }
281 }
282}
283
284pub use launch::*;