-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathserver.rs
More file actions
294 lines (257 loc) · 9.73 KB
/
server.rs
File metadata and controls
294 lines (257 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use std::sync::Arc;
use cubecl_common::{bytes::Bytes, profile::ProfileDuration};
use cubecl_core::{
CubeCount, ExecutionMode, MemoryUsage,
compute::CubeTask,
future::DynFut,
server::{
Allocation, AllocationDescriptor, Binding, Bindings, ComputeServer, CopyDescriptor,
DataTransferService, Handle, IoError, ProfileError, ProfilingToken,
},
};
use cubecl_runtime::{
logging::ServerLogger,
memory_management::{MemoryManagement, offset_handles},
storage::{BindingResource, BytesStorage, ComputeStorage},
timestamp_profiler::TimestampProfiler,
};
use crate::{CpuCompiler, compute::alloc_controller::CpuAllocController};
use cubecl_runtime::stride::{contiguous_strides, pitched_rows_layout, row_pitch_elems};
use super::scheduler::Scheduler;
#[derive(Debug)]
pub struct CpuServer {
ctx: CpuContext,
scheduler: Scheduler,
logger: ServerLogger,
}
impl DataTransferService for CpuServer {}
impl CpuServer {
pub fn new(ctx: CpuContext) -> Self {
Self {
logger: ServerLogger::default(),
scheduler: Scheduler::default(),
ctx,
}
}
}
#[derive(Debug)]
pub struct CpuContext {
memory_management: MemoryManagement<BytesStorage>,
timestamps: TimestampProfiler,
}
impl CpuContext {
pub fn new(memory_management: MemoryManagement<BytesStorage>) -> Self {
Self {
memory_management,
timestamps: TimestampProfiler::default(),
}
}
}
impl CpuServer {
fn read_async(
&mut self,
descriptors: Vec<CopyDescriptor>,
) -> impl Future<Output = Result<Vec<Bytes>, IoError>> + Send + use<> {
fn inner(
ctx: &mut CpuContext,
descriptors: Vec<CopyDescriptor>,
) -> Result<Vec<Bytes>, IoError> {
let mut result = Vec::with_capacity(descriptors.len());
for desc in descriptors {
let binding = desc.binding;
let elem = desc.elem_size;
let size = desc.shape.iter().product::<usize>() * elem;
// Contiguous: return zero-copy Bytes over the binding with logical len
if contiguous_strides(desc.shape) == desc.strides {
let (controller, alloc) =
CpuAllocController::init(binding, &mut ctx.memory_management)?;
result
.push(unsafe { Bytes::from_raw_parts(alloc, size, Box::new(controller)) });
continue;
}
// Inner-contiguous rows: reconstruct rows into contiguous buffer
if let Some(row_pitch_elems) = row_pitch_elems(desc.shape, desc.strides) {
let resource = ctx
.memory_management
.get_resource(binding.memory, binding.offset_start, binding.offset_end)
.ok_or(IoError::InvalidHandle)?;
let last = desc.shape.len() - 1;
let rows = desc.shape[..last].iter().product::<usize>();
let cols = desc.shape[last];
let row_bytes = cols * elem;
let row_pitch = row_pitch_elems * elem;
let src = resource.read();
let mut out = vec![0u8; rows * row_bytes];
for r in 0..rows {
let src_off = r * row_pitch;
let dst_off = r * row_bytes;
out[dst_off..dst_off + row_bytes]
.copy_from_slice(&src[src_off..src_off + row_bytes]);
}
result.push(Bytes::from_bytes_vec(out));
continue;
}
return Err(IoError::UnsupportedStrides);
}
Ok(result)
}
let res = inner(&mut self.ctx, descriptors);
async move { res }
}
}
impl ComputeServer for CpuServer {
type Kernel = Box<dyn CubeTask<CpuCompiler>>;
type Storage = BytesStorage;
type Info = ();
fn create(
&mut self,
descriptors: Vec<AllocationDescriptor<'_>>,
) -> Result<Vec<Allocation>, IoError> {
let align = 8;
let mut strides = Vec::with_capacity(descriptors.len());
let mut sizes = Vec::with_capacity(descriptors.len());
use cubecl_core::server::AllocationKind;
for desc in &descriptors {
let rank = desc.shape.len();
if matches!(desc.kind, AllocationKind::Optimized) && rank > 1 {
let (s, size) = pitched_rows_layout(desc.shape, desc.elem_size, align);
strides.push(s);
sizes.push(size);
} else {
strides.push(contiguous_strides(desc.shape));
sizes.push(desc.shape.iter().product::<usize>() * desc.elem_size);
}
}
let total_size = sizes
.iter()
.map(|it| it.next_multiple_of(align))
.sum::<usize>();
let handle = self.ctx.memory_management.reserve(total_size as u64)?;
let mem_handle = Handle::new(handle, None, None, total_size as u64);
let handles = offset_handles(mem_handle, &sizes, align);
Ok(handles
.into_iter()
.zip(strides)
.map(|(handle, strides)| Allocation::new(handle, strides))
.collect())
}
fn read<'a>(
&mut self,
descriptors: Vec<CopyDescriptor<'a>>,
) -> DynFut<Result<Vec<Bytes>, IoError>> {
Box::pin(self.read_async(descriptors))
}
fn write(&mut self, descriptors: Vec<(CopyDescriptor<'_>, &[u8])>) -> Result<(), IoError> {
for (desc, data) in descriptors {
// Contiguous path
if contiguous_strides(desc.shape) == desc.strides {
self.copy_to_binding(desc.binding, data);
continue;
}
// Inner-contiguous rows: copy into pitched destination row-by-row
if let Some(row_pitch_elems) = row_pitch_elems(desc.shape, desc.strides) {
let last = desc.shape.len() - 1;
let rows = desc.shape[..last].iter().product::<usize>();
let cols = desc.shape[last];
let elem = desc.elem_size;
let row_bytes = cols * elem;
let row_pitch = row_pitch_elems * elem;
let resource = self
.ctx
.memory_management
.get_resource(
desc.binding.memory,
desc.binding.offset_start,
desc.binding.offset_end,
)
.ok_or(IoError::InvalidHandle)?;
let dst = resource.write();
for r in 0..rows {
let dst_off = r * row_pitch;
let src_off = r * row_bytes;
dst[dst_off..dst_off + row_bytes]
.copy_from_slice(&data[src_off..src_off + row_bytes]);
}
continue;
}
return Err(IoError::UnsupportedStrides);
}
Ok(())
}
fn memory_usage(&self) -> MemoryUsage {
self.ctx.memory_management.memory_usage()
}
fn memory_cleanup(&mut self) {
self.ctx.memory_management.cleanup(true)
}
unsafe fn execute(
&mut self,
kernel: Self::Kernel,
count: CubeCount,
bindings: Bindings,
kind: ExecutionMode,
_logger: Arc<ServerLogger>,
) {
let cube_count = match count {
CubeCount::Static(x, y, z) => [x, y, z],
CubeCount::Dynamic(binding) => {
let handle = self
.ctx
.memory_management
.get_resource(binding.memory, binding.offset_start, binding.offset_end)
.expect("Failed to find resource");
let bytes = handle.read();
let x = u32::from_ne_bytes(bytes[0..4].try_into().unwrap());
let y = u32::from_ne_bytes(bytes[4..8].try_into().unwrap());
let z = u32::from_ne_bytes(bytes[8..12].try_into().unwrap());
[x, y, z]
}
};
self.scheduler.dispatch_execute(
kernel,
cube_count,
bindings,
kind,
&mut self.ctx.memory_management,
);
}
fn flush(&mut self) {}
fn sync(&mut self) -> DynFut<()> {
self.logger.profile_summary();
Box::pin(async move {})
}
fn start_profile(&mut self) -> ProfilingToken {
cubecl_common::future::block_on(self.sync());
self.ctx.timestamps.start()
}
fn end_profile(&mut self, token: ProfilingToken) -> Result<ProfileDuration, ProfileError> {
self.logger.profile_summary();
cubecl_common::future::block_on(self.sync());
self.ctx.timestamps.stop(token)
}
fn get_resource(
&mut self,
binding: Binding,
) -> BindingResource<<Self::Storage as ComputeStorage>::Resource> {
BindingResource::new(
binding.clone(),
self.ctx
.memory_management
.get_resource(binding.memory, binding.offset_start, binding.offset_end)
.expect("Can't find resource"),
)
}
fn allocation_mode(&mut self, mode: cubecl_runtime::memory_management::MemoryAllocationMode) {
self.ctx.memory_management.mode(mode);
}
}
impl CpuServer {
fn copy_to_binding(&mut self, binding: Binding, data: &[u8]) {
let resource = self
.ctx
.memory_management
.get_resource(binding.memory, binding.offset_start, binding.offset_end)
.unwrap();
resource.write().copy_from_slice(data);
}
}