Source file view.ml
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
type layout = C_contiguous | Strided
type t = {
shape : Symbolic_shape.t;
strides : int array;
offset : int;
mask : (int * int) array option;
layout : layout;
}
let prod arr = Array.fold_left ( * ) 1 arr
let compute_strides shape_array =
let n = Array.length shape_array in
if n = 0 then [||]
else
let strides = Array.make n 0 in
strides.(n - 1) <- (if shape_array.(n - 1) = 0 then 0 else 1);
for i = n - 2 downto 0 do
strides.(i) <-
(if shape_array.(i) = 0 then 0
else strides.(i + 1) * max 1 shape_array.(i + 1))
done;
strides
let canonicalize_strides _shape_array strides = strides
let eval_shape_opt shape = Symbolic_shape.eval shape
let is_c_contiguous_strides shape_arr strides offset mask =
offset = 0 && mask = None
&&
let expected = compute_strides shape_arr in
let expected_canonical = canonicalize_strides shape_arr expected in
Array.length strides = Array.length expected_canonical
&& Array.for_all2 ( = ) strides expected_canonical
let shape v = v.shape
let strides v = v.strides
let stride axis v =
let ndim = Symbolic_shape.rank v.shape in
if axis < 0 || axis >= ndim then
Error.axis_out_of_bounds ~op:"stride" ~axis ~ndim ();
Array.unsafe_get v.strides axis
let offset v = v.offset
let mask v = v.mask
let is_c_contiguous v = v.layout = C_contiguous
let dim axis v =
let ndim = Symbolic_shape.rank v.shape in
if axis < 0 || axis >= ndim then
Error.axis_out_of_bounds ~op:"dim" ~axis ~ndim ();
v.shape.(axis)
let ndim v = Symbolic_shape.rank v.shape
let numel v =
let n = Symbolic_shape.rank v.shape in
if n = 0 then Symbolic_shape.static 1
else
let rec prod_dims i acc =
if i >= n then acc
else
let next_acc =
match
(Symbolic_shape.eval_dim acc, Symbolic_shape.eval_dim v.shape.(i))
with
| Some a, Some b -> Symbolic_shape.static (a * b)
| _ -> Symbolic_shape.mul acc v.shape.(i)
in
prod_dims (i + 1) next_acc
in
prod_dims 1 v.shape.(0)
let create ?(offset = 0) ?strides ?mask shape =
match Symbolic_shape.eval shape with
| Some shape_arr ->
let is_zero_size = Array.exists (( = ) 0) shape_arr in
let current_shape =
if is_zero_size then
Symbolic_shape.of_ints (Array.map (fun s -> max s 0) shape_arr)
else shape
in
let current_strides =
match strides with
| Some s -> canonicalize_strides shape_arr s
| None -> compute_strides shape_arr
in
let current_offset = if is_zero_size then 0 else offset in
let current_mask =
if is_zero_size then None
else
match mask with
| Some m
when Array.for_all2 (fun (b, e) s -> b = 0 && e = s) m shape_arr ->
None
| _ -> mask
in
let new_layout =
if
is_c_contiguous_strides shape_arr current_strides current_offset
current_mask
then C_contiguous
else Strided
in
{
shape = current_shape;
strides = current_strides;
offset = current_offset;
mask = current_mask;
layout = new_layout;
}
| None ->
let symbolic_strides =
match strides with
| Some s -> s
| None ->
let n = Symbolic_shape.rank shape in
if n = 0 then [||]
else
let strides = Array.make n 1 in
for i = n - 2 downto 0 do
strides.(i) <- strides.(i + 1)
done;
strides
in
let layout =
if offset = 0 && mask = None && strides = None then C_contiguous
else Strided
in
{ shape; strides = symbolic_strides; offset; mask; layout }
let linear_index view indices =
let ndim = Symbolic_shape.rank view.shape in
if Array.length indices <> ndim then
Error.invalid ~op:"linear_index" ~what:"indices"
~reason:
(Printf.sprintf "rank mismatch: %d vs %d" (Array.length indices) ndim)
();
let physical_offset = ref view.offset in
Array.iteri
(fun i idx ->
physical_offset := !physical_offset + (idx * view.strides.(i)))
indices;
!physical_offset
let is_valid view indices =
match view.mask with
| None -> true
| Some mask_array ->
if Array.length indices <> Array.length mask_array then false
else
Array.for_all2
(fun idx (b, e) -> idx >= b && idx < e)
indices mask_array
let can_be_strided view =
match (view.mask, eval_shape_opt view.shape) with
| None, _ -> true
| Some mask_array, Some shape_arr ->
Array.for_all2 (fun (b, e) s -> b = 0 && e = s) mask_array shape_arr
| Some _, None ->
false
let expand view new_shape =
let old_ndim = Symbolic_shape.rank view.shape in
let new_ndim = Symbolic_shape.rank new_shape in
if old_ndim = 0 then
let strides = Array.make new_ndim 0 in
{ view with shape = new_shape; strides }
else if new_ndim <> old_ndim then
Error.invalid ~op:"expand" ~what:"shape dimensions"
~reason:(Printf.sprintf "rank mismatch: %d vs %d" new_ndim old_ndim)
()
else
match (Symbolic_shape.eval view.shape, Symbolic_shape.eval new_shape) with
| Some old_arr, Some new_arr ->
if Array.exists (( = ) 0) old_arr then create new_shape
else
let strides =
Array.mapi
(fun i ns ->
let s = old_arr.(i) in
if s = ns then view.strides.(i)
else if s = 1 then 0
else
Error.cannot ~op:"expand" ~what:"expand"
~from:(Printf.sprintf "dimension %d (size %d)" i s)
~to_:(Printf.sprintf "size %d" ns)
~reason:"can only expand singleton dimensions" ())
new_arr
in
let mask =
match view.mask with
| None -> None
| Some m ->
Some
(Array.mapi
(fun i (b, e) ->
if old_arr.(i) = 1 && new_arr.(i) <> 1 then
if b = 0 && e = 1 then (0, new_arr.(i))
else
Error.invalid ~op:"expand"
~what:"masked singleton dimension"
~reason:
(Printf.sprintf
"bounds [%d,%d] incompatible with expansion" b
e)
()
else (b, e))
m)
in
create ~offset:view.offset ?mask ~strides new_shape
| _, _ ->
create ~offset:view.offset ?mask:view.mask ~strides:view.strides
new_shape
let permute view axes =
let n = ndim view in
if Array.length axes <> n then
Error.invalid ~op:"permute" ~what:"axes array"
~reason:(Printf.sprintf "length %d != ndim %d" (Array.length axes) n)
();
let seen = Array.make n false in
Array.iter
(fun ax ->
if ax < 0 || ax >= n then
Error.axis_out_of_bounds ~op:"permute" ~axis:ax ~ndim:n ();
if seen.(ax) then
Error.invalid ~op:"permute"
~what:(Printf.sprintf "axis %d" ax)
~reason:"duplicate axis" ();
seen.(ax) <- true)
axes;
let new_shape = Array.init n (fun i -> view.shape.(axes.(i))) in
let new_strides = Array.init n (fun i -> view.strides.(axes.(i))) in
let new_mask =
Option.map (fun m -> Array.init n (fun i -> m.(axes.(i)))) view.mask
in
create ~offset:view.offset ?mask:new_mask ~strides:new_strides
(Array.of_list (Array.to_list new_shape))
let reshape view new_shape =
if Symbolic_shape.equal view.shape new_shape then view
else
match (Symbolic_shape.eval view.shape, Symbolic_shape.eval new_shape) with
| Some old_arr, Some new_arr -> (
let old_numel = prod old_arr in
let new_numel = prod new_arr in
if old_numel <> new_numel && old_numel <> 0 && new_numel <> 0 then
Error.shape_mismatch ~op:"reshape" ~expected:new_arr ~actual:old_arr
()
else if Array.exists (( = ) 0) old_arr || Array.exists (( = ) 0) new_arr
then create ~offset:0 new_shape
else if view.mask <> None then
Error.failed ~op:"reshape" ~what:"cannot reshape views with masks"
~hint:"call contiguous() first to create a mask-free copy" ()
else if view.layout = C_contiguous then
create ~offset:view.offset new_shape
else if
Array.length new_shape = 0
then
create ~offset:view.offset new_shape
else if Array.for_all (( = ) 0) view.strides then
let new_strides = Array.make (Array.length new_shape) 0 in
create ~offset:view.offset ~strides:new_strides new_shape
else
let _old_non_one = Array.to_list old_arr |> List.filter (( <> ) 1) in
let _new_non_one = Array.to_list new_arr |> List.filter (( <> ) 1) in
let try_squeeze_unsqueeze () =
let old_non_one = Array.to_list old_arr |> List.filter (( <> ) 1) in
let new_non_one = Array.to_list new_arr |> List.filter (( <> ) 1) in
if old_non_one = new_non_one then
let old_idx = ref 0 in
let new_strides =
Array.map
(fun dim ->
if dim = 1 then 0
else (
while
!old_idx < Array.length old_arr
&& old_arr.(!old_idx) = 1
do
incr old_idx
done;
let stride = view.strides.(!old_idx) in
incr old_idx;
stride))
new_arr
in
Some new_strides
else None
in
let try_merge_split () =
let old_dims = ref [] in
let new_dims = ref [] in
for i = 0 to Array.length old_arr - 1 do
if old_arr.(i) > 1 then
old_dims := (old_arr.(i), view.strides.(i)) :: !old_dims
done;
old_dims := List.rev !old_dims;
for i = 0 to Array.length new_arr - 1 do
if new_arr.(i) > 1 then new_dims := new_arr.(i) :: !new_dims
done;
new_dims := List.rev !new_dims;
let rec match_dims old_dims new_dims =
match (old_dims, new_dims) with
| [], [] -> Some []
| [], _ | _, [] -> None
| (old_size, old_stride) :: old_rest, new_size :: new_rest ->
if old_size = new_size then
match match_dims old_rest new_rest with
| Some rest_strides ->
Some ((new_size, old_stride) :: rest_strides)
| None -> None
else if old_size > new_size && old_size mod new_size = 0 then
let remaining_size = old_size / new_size in
let first_stride = old_stride * remaining_size in
let remaining_dims =
(remaining_size, old_stride) :: old_rest
in
match match_dims remaining_dims new_rest with
| Some rest_strides ->
Some ((new_size, first_stride) :: rest_strides)
| None -> None
else if new_size > old_size then
let rec collect_merge size stride dims needed =
if size = needed then Some (dims, stride)
else if size > needed then None
else
match dims with
| [] -> None
| (next_size, next_stride) :: rest ->
if stride = next_stride * next_size then
collect_merge (size * next_size) next_stride rest
needed
else None
in
match
collect_merge old_size old_stride old_rest new_size
with
| Some (remaining, first_stride) -> (
match match_dims remaining new_rest with
| Some rest_strides ->
Some ((new_size, first_stride) :: rest_strides)
| None -> None)
| None -> None
else None
in
match match_dims !old_dims !new_dims with
| None -> None
| Some stride_map ->
let new_strides = Array.make (Array.length new_arr) 0 in
let map_idx = ref 0 in
for i = 0 to Array.length new_arr - 1 do
if new_arr.(i) = 1 then new_strides.(i) <- 0
else
let _, stride = List.nth stride_map !map_idx in
new_strides.(i) <- stride;
incr map_idx
done;
Some new_strides
in
match try_squeeze_unsqueeze () with
| Some new_strides ->
create ~offset:view.offset ~strides:new_strides new_shape
| None -> (
match try_merge_split () with
| Some new_strides ->
create ~offset:view.offset ~strides:new_strides new_shape
| None ->
let expected_strides = compute_strides new_arr in
let stride_str =
"["
^ String.concat ","
(Array.to_list (Array.map string_of_int view.strides))
^ "]"
in
let expected_str =
"["
^ String.concat ","
(Array.to_list
(Array.map string_of_int expected_strides))
^ "]"
in
Error.cannot ~op:"reshape" ~what:"reshape strided view"
~from:(Shape.to_string old_arr)
~to_:(Shape.to_string new_arr)
~reason:
(Printf.sprintf "incompatible strides %s (expected %s)"
stride_str expected_str)
~hint:
"call contiguous() before reshape to create a \
C-contiguous copy"
()))
| _, _ ->
if view.layout = C_contiguous then create ~offset:view.offset new_shape
else
Error.failed ~op:"reshape"
~what:"cannot reshape symbolic non-contiguous view"
~hint:"bind all symbolic dimensions before reshaping" ()
let unsafe_resize view arg new_mask_opt =
let ndim = Symbolic_shape.rank view.shape in
if Array.length arg <> ndim then
Error.invalid ~op:"unsafe_resize" ~what:"argument array"
~reason:(Printf.sprintf "length %d != ndim %d" (Array.length arg) ndim)
();
let strides = view.strides in
let new_shape = Array.map (fun (a, b) -> b - a) arg in
let new_offset = ref view.offset in
Array.iteri
(fun i (a, _) -> new_offset := !new_offset + (a * strides.(i)))
arg;
let final_mask =
let shift_and_combine_mask old_mask_dim_bounds new_mask_dim_bounds
offset_for_dim =
let old_b, old_e = old_mask_dim_bounds in
let new_b, new_e = new_mask_dim_bounds in
let shifted_old_b = max 0 (old_b - offset_for_dim) in
let shifted_old_e = max 0 (old_e - offset_for_dim) in
(max shifted_old_b new_b, min shifted_old_e new_e)
in
match (view.mask, new_mask_opt) with
| None, None -> None
| Some old_m, None ->
Some
(Array.mapi
(fun i (old_b, old_e) ->
let a, _ = arg.(i) in
let new_dim_size = new_shape.(i) in
(max 0 (old_b - a), min new_dim_size (old_e - a)))
old_m)
| None, Some new_m -> Some new_m
| Some old_m, Some new_m ->
Some
(Array.mapi
(fun i (old_b_i, old_e_i) ->
let new_m_b_i, new_m_e_i = new_m.(i) in
let a_i, _ = arg.(i) in
shift_and_combine_mask (old_b_i, old_e_i) (new_m_b_i, new_m_e_i)
a_i)
old_m)
in
create ~offset:!new_offset ?mask:final_mask ~strides
(Symbolic_shape.of_ints new_shape)
let pad view arg =
let ndim = Symbolic_shape.rank view.shape in
if Array.length arg <> ndim then
Error.invalid ~op:"pad" ~what:"padding array"
~reason:(Printf.sprintf "length %d != ndim %d" (Array.length arg) ndim)
();
if Array.for_all (fun (b, e) -> b = 0 && e = 0) arg then view
else if Array.exists (fun (b, e) -> b < 0 || e < 0) arg then
Error.invalid ~op:"pad" ~what:"padding values"
~reason:"negative values not allowed"
~hint:"use shrink or slice to remove elements" ()
else
match eval_shape_opt view.shape with
| None ->
Error.failed ~op:"pad" ~what:"cannot pad symbolic shape"
~hint:"bind all symbolic dimensions before padding" ()
| Some shape_arr ->
let zvarg =
Array.mapi
(fun i s ->
let pad_before, pad_after = arg.(i) in
(-pad_before, s + pad_after))
shape_arr
in
let mask_for_pad =
Array.mapi
(fun i s_old ->
let pad_before, _pad_after = arg.(i) in
(pad_before, pad_before + s_old))
shape_arr
in
unsafe_resize view zvarg (Some mask_for_pad)
let shrink view arg =
let ndim = Symbolic_shape.rank view.shape in
if Array.length arg <> ndim then
Error.invalid ~op:"shrink" ~what:"bounds array"
~reason:(Printf.sprintf "length %d != ndim %d" (Array.length arg) ndim)
();
match eval_shape_opt view.shape with
| None ->
Error.failed ~op:"shrink" ~what:"cannot shrink symbolic shape"
~hint:"bind all symbolic dimensions before shrinking" ()
| Some shape_arr ->
if Array.for_all2 (fun (b, e) s -> b = 0 && e = s) arg shape_arr then view
else if
Array.exists2
(fun (b, e) s -> b < 0 || e < 0 || b > s || e > s || b >= e)
arg shape_arr
then
Error.invalid ~op:"shrink" ~what:"bounds"
~reason:"must be within shape and start < end" ()
else unsafe_resize view arg None
let flip view flip_axes_bools =
let ndim = Symbolic_shape.rank view.shape in
if Array.length flip_axes_bools <> ndim then
Error.invalid ~op:"flip" ~what:"boolean array"
~reason:
(Printf.sprintf "length %d != ndim %d"
(Array.length flip_axes_bools)
ndim)
();
match eval_shape_opt view.shape with
| None ->
Error.failed ~op:"flip" ~what:"cannot flip symbolic shape"
~hint:"bind all symbolic dimensions before flipping" ()
| Some shape_arr ->
let strides = view.strides in
let new_offset = ref view.offset in
let new_strides = Array.copy strides in
let new_mask =
match view.mask with Some m -> Some (Array.copy m) | None -> None
in
Array.iteri
(fun i do_flip ->
if do_flip then
let s_i = shape_arr.(i) in
if s_i > 0 then (
new_offset := !new_offset + ((s_i - 1) * strides.(i));
new_strides.(i) <- -new_strides.(i);
match new_mask with
| Some m_arr ->
let b, e = m_arr.(i) in
m_arr.(i) <- (s_i - e, s_i - b)
| None -> ()))
flip_axes_bools;
create ~offset:!new_offset ?mask:new_mask ~strides:new_strides view.shape
let merge v1 v2 =
if v2.layout = C_contiguous then
if v1.layout = C_contiguous then
try Some (reshape v1 v2.shape) with _ -> None
else
None
else if v1.layout = C_contiguous && Symbolic_shape.equal v1.shape v2.shape
then Some v2
else if
(not (Symbolic_shape.is_static v1.shape))
|| not (Symbolic_shape.is_static v2.shape)
then
if v1.layout = C_contiguous then
Some { v2 with offset = v1.offset + v2.offset }
else
None
else if v1.layout = C_contiguous then
match (Symbolic_shape.eval v1.shape, Symbolic_shape.eval v2.shape) with
| Some s1_arr, Some s2_arr when prod s1_arr = prod s2_arr -> (
let v2_is_permutation =
match (Symbolic_shape.eval v2.shape, v2.strides) with
| Some shape_arr, strides ->
let non_unit_pairs =
Array.to_list
(Array.mapi
(fun i _ -> (shape_arr.(i), strides.(i)))
shape_arr)
|> List.filter (fun (size, _) -> size > 1)
in
if List.length non_unit_pairs < 2 then
false
else
let strides_only =
List.map snd non_unit_pairs |> Array.of_list
in
let expected_strides =
let sizes_only =
List.map fst non_unit_pairs |> Array.of_list
in
compute_strides sizes_only
in
not (Array.for_all2 ( = ) strides_only expected_strides)
| _ -> false
in
if v2_is_permutation then
None
else
try Some (reshape v1 v2.shape) with _ -> None)
| _ -> None
else if Array.exists (( = ) 0) v1.strides then
match Symbolic_shape.eval v2.shape with
| Some _s2_arr ->
Some v2
| _ -> None
else if v1.mask = None && v2.mask = None then
match (Symbolic_shape.eval v1.shape, Symbolic_shape.eval v2.shape) with
| Some s1_arr, Some s2_arr when Array.length s1_arr = Array.length s2_arr ->
let is_expand = ref true in
for i = 0 to Array.length s1_arr - 1 do
if s1_arr.(i) <> s2_arr.(i) && s1_arr.(i) <> 1 then is_expand := false
done;
let has_negative_v1 = Array.exists (fun s -> s < 0) v1.strides in
let has_negative_v2 = Array.exists (fun s -> s < 0) v2.strides in
if !is_expand && has_negative_v1 = has_negative_v2 then
try Some (expand v1 v2.shape) with _ -> None
else None
| _ -> None
else if v2.mask <> None && v1.mask = None then
Some v2
else None
let simplify view =
match Symbolic_shape.eval view.shape with
| None -> view
| Some shape_arr ->
let mask =
match view.mask with
| Some m
when Array.for_all2 (fun (b, e) s -> b = 0 && e = s) m shape_arr ->
None
| m -> m
in
if mask <> view.mask then
let new_layout =
if
mask = None && view.offset = 0
&& is_c_contiguous_strides shape_arr view.strides 0 None
then C_contiguous
else Strided
in
{ view with mask; layout = new_layout }
else view