-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconscious_struct.py
executable file
·1547 lines (1297 loc) · 51.4 KB
/
conscious_struct.py
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# TODO: design a way to "observe" current holding keys, current mouse location, encode that observation and feed into model input along with screen image data
# import pynput
# no such dependency when training.
import einops
import os
import numpy as np
import cv2
import ast
from pydantic import BaseModel, validator
from typing import Union, Mapping, List
# import logging
from log_utils import logger
from pydantic_numpy import NDArray
import torch
try:
from typing import Literal
except:
from typing_extensions import Literal # this is a failsafe.
try:
from typing import TypeAlias
except:
from typing_extensions import TypeAlias
##############
# HID BASE #
##############
class HIDActionTypes:
keyboard_action_types: TypeAlias = Literal[
"key_press",
"key_release",
]
mouse_action_types: TypeAlias = Literal[
"mouse_move",
"mouse_click",
"mouse_scroll",
]
action_types: TypeAlias = Literal[
keyboard_action_types,
mouse_action_types,
]
mouse_buttons: TypeAlias = Literal[
"Button.left",
"Button.middle",
"Button.right",
]
keys: TypeAlias = Literal[
"""','""",
"""'.'""",
"""'/'""",
"""';'""",
"""\"'\"""",
"""'['""",
"""']'""",
"""'\\'""",
"""'='""",
"""'-'""",
"""'0'""",
"""'9'""",
"""'8'""",
"""'7'""",
"""'6'""",
"""'5'""",
"""'4'""",
"""'3'""",
"""'2'""",
"""'1'""",
"""'`'""",
"""'a'""",
"""'b'""",
"""'c'""",
"""'d'""",
"""'e'""",
"""'f'""",
"""'g'""",
"""'h'""",
"""'i'""",
"""'j'""",
"""'k'""",
"""'l'""",
"""'m'""",
"""'n'""",
"""'o'""",
"""'p'""",
"""'q'""",
"""'r'""",
"""'s'""",
"""'t'""",
"""'u'""",
"""'v'""",
"""'w'""",
"""'x'""",
"""'y'""",
"""'z'""",
"Key.alt", # check pynput.keyboard.Key
"Key.alt_r",
"Key.backspace",
"Key.caps_lock",
"Key.cmd",
"Key.cmd_r",
"Key.ctrl",
"Key.ctrl_r",
"Key.delete",
"Key.down",
"Key.end",
"Key.enter",
"Key.esc",
"Key.f1",
"Key.f2",
"Key.f3",
"Key.f4",
"Key.f5",
"Key.f6",
"Key.f7",
"Key.f8",
"Key.f9",
"Key.f10",
"Key.f11",
"Key.f12",
"Key.f13",
"Key.f14",
"Key.f15",
"Key.f16",
"Key.f17",
"Key.f18",
"Key.f19",
"Key.f20",
"Key.home",
"Key.left",
"Key.page_down",
"Key.page_up",
"Key.right",
"Key.shift",
"Key.shift_r",
"Key.space",
"Key.tab",
"Key.up",
]
class HIDActionBase:
mouse_resolution: int = 1000
keyboard_action_types = list(HIDActionTypes.keyboard_action_types.__args__)
mouse_action_types = list(HIDActionTypes.mouse_action_types.__args__)
action_types = list(HIDActionTypes.action_types.__args__)
mouse_buttons = list(HIDActionTypes.mouse_buttons.__args__)
keys = list(HIDActionTypes.keys.__args__)
length = (
len(action_types)
+ len(keys)
+ len(mouse_buttons)
+ 1 # mouse pressed
+ 4 * mouse_resolution
) # ,
# 1)
@staticmethod
def unshift_keycode(keycode: str) -> Union[str, None]:
unshift_keycodes = {
"!": "1",
"@": "2",
"#": "3",
"$": "4",
"%": "5",
"^": "6",
"&": "7",
"*": "8",
"(": "9",
")": "0",
"_": "-",
"+": "=",
"{": "[",
"}": "]",
"|": "\\",
":": ";",
'"': "'",
"<": ",",
">": ".",
"?": "/",
"~": "`",
}
ctrl_keycodes = {
"\x01": "a",
"\x02": "b",
"\x03": "c",
"\x04": "d",
"\x05": "e",
"\x06": "f",
"\x07": "g",
"\x08": "h",
"\t": "i",
"\n": "j",
"\x0b": "k",
"\x0c": "l",
"\r": "m",
"\x0e": "n",
"\x0f": "o",
"\x10": "p",
"\x11": "q",
"\x12": "r",
"\x13": "s",
"\x14": "t",
"\x15": "u",
"\x16": "v",
"\x17": "w",
"\x18": "x",
"\x19": "y",
"\x1a": "z",
"<219>": "[",
"<221>": "]",
"<189>": "-",
"<187>": "=",
"<192>": "`",
"<48>": "0",
"<49>": "1",
"<50>": "2",
"<51>": "3",
"<52>": "4",
"<53>": "5",
"<54>": "6",
"<55>": "7",
"<56>": "8",
"<57>": "9",
"<220>": "\\",
"<186>": ";",
"<222>": "'",
"<188>": ",",
"<190>": ".",
"<191>": "/",
}
keycode = unshift_keycodes.get(keycode, ctrl_keycodes.get(keycode, keycode))
# still, this is something out of concern.
if keycode.startswith("<") and keycode.endswith(">"):
logger.warning("Discarding unconvertable keycode: %s" % keycode)
# keycode = pynput.keyboard.KeyCode(int(keycode[1:-1]))
return
return keycode
@staticmethod
def uncover_keycode(keycode: str) -> Union[str, None]:
if not keycode.startswith("Key."):
keycode_converted = HIDActionBase.unshift_keycode(
keycode
if keycode.startswith("<") and keycode.endswith(">")
else ast.literal_eval(keycode)
)
return keycode_converted
# this could be None.
# when this is None, simply skip this code. do not end the conversion. skip it.
else:
return keycode
class HIDAction(BaseModel, HIDActionBase):
# static method: from_action
# static method: from_ndarray
# instance method: to_ndarray
# instance method: to_action
max_x: int
max_y: int
action_type: Literal[
"key_press", # ["key_press", "'w'"]
"key_release", # ["key_release", "'r'"]
"mouse_move", # ["mouse_move", [176.7734375, 580.40625]], "timeStamp": 1680247557.125498}
"mouse_click", # ["mouse_click", [176.7734375, 580.40625, "Button.left", true]]
"mouse_scroll", # ["mouse_scroll", [938.76171875, 318.75, 0, 0]]
# None, # end_of_action
] # you need to specify this.
key: Union[
HIDActionTypes.keys,
None,
] = None
mouse_button: Union[HIDActionTypes.mouse_buttons, None] = None
mouse_pressed: Union[bool, None] = None
x: Union[float, None] = None
y: Union[float, None] = None
dx: Union[float, None] = None
dy: Union[float, None] = None
@validator("max_x", "max_y")
def greater_than_zero(cls, v):
assert type(v) == int
assert v > 0
return v
@validator("action_type")
def action_type_within_action_types(cls, v):
if v:
assert v in HIDActionBase.action_types
return v
@validator("key")
def key_within_keys(cls, v):
if v:
assert v in HIDActionBase.keys
return v
@validator("mouse_button")
def mouse_button_within_mouse_buttons(cls, v):
if v:
assert v in HIDActionBase.mouse_buttons
return v
@validator("mouse_pressed")
def mouse_pressed_type_check(cls, v):
if v:
assert type(v) == bool
return v
@staticmethod
def from_action_json(action_json: list, max_x: int, max_y: int):
action_type = action_json[0]
action_args = action_json[1]
construct_args = dict(max_x=max_x, max_y=max_y, action_type=action_type)
# BUG: convert single char keys to quoted format.
# TODO: make sure ' ' is converted into Key.Space
if action_type.startswith("key"):
if len(action_args) == 1:
if action_args != "'":
action_args = f"'{action_args}'"
else:
action_args = f'"{action_args}"'
if action_args == repr(" "):
action_args = "Key.space"
if action_type == "key_press":
assert action_args in HIDActionBase.keys
construct_args.update(dict(key=action_args))
elif action_type == "key_release":
assert action_args in HIDActionBase.keys
construct_args.update(dict(key=action_args))
elif action_type == "mouse_move":
assert action_args[0] >= 0 and action_args[0] <= max_x
assert action_args[1] >= 0 and action_args[1] <= max_y
construct_args.update(dict(x=action_args[0], y=action_args[1]))
elif action_type == "mouse_click":
assert action_args[0] >= 0 and action_args[0] <= max_x
assert action_args[1] >= 0 and action_args[1] <= max_y
assert action_args[2] in HIDActionBase.mouse_buttons
assert type(action_args[3]) == bool
construct_args.update(
dict(
x=action_args[0],
y=action_args[1],
mouse_button=action_args[2],
mouse_pressed=action_args[3],
)
)
elif action_type == "mouse_scroll":
assert action_args[0] >= 0 and action_args[0] <= max_x
assert action_args[1] >= 0 and action_args[1] <= max_y
assert action_args[2] >= -max_x and action_args[2] <= max_x
assert action_args[3] >= -max_y and action_args[3] <= max_y
construct_args.update(
dict(
x=action_args[0],
y=action_args[1],
dx=action_args[2],
dy=action_args[3],
)
)
else:
raise Exception(
"Unknown action type: %s\naction args: %s" % (action_type, action_args)
)
mHIDAction = HIDAction(**construct_args)
return mHIDAction
@staticmethod
def from_ndarray(ndarray: np.ndarray, max_x: int, max_y: int):
assert ndarray.shape == (HIDActionBase.length,)
cursor = 0
action_type_ndarray = ndarray[cursor : cursor + len(HIDActionBase.action_types)]
cursor += len(HIDActionBase.action_types)
action_type_index = np.argmax(action_type_ndarray)
action_type = HIDActionBase.action_types[action_type_index]
del action_type_ndarray
del action_type_index
construct_args = dict(max_x=max_x, max_y=max_y, action_type=action_type)
if action_type:
key_ndarray = ndarray[cursor : cursor + len(HIDActionBase.keys)]
cursor += len(HIDActionBase.keys)
key_index = np.argmax(key_ndarray)
key = HIDActionBase.keys[key_index]
del key_ndarray
del key_index
mouse_button_ndarray = ndarray[
cursor : cursor + len(HIDActionBase.mouse_buttons)
]
cursor += len(HIDActionBase.mouse_buttons)
mouse_button_index = np.argmax(mouse_button_ndarray)
mouse_button = HIDActionBase.mouse_buttons[mouse_button_index]
del mouse_button_ndarray
del mouse_button_index
mouse_pressed_ndarray = ndarray[cursor : cursor + 1]
cursor += 1
mouse_pressed = bool(mouse_pressed_ndarray[0][0])
del mouse_pressed_ndarray
x_ndarray = ndarray[cursor : cursor + HIDActionBase.mouse_resolution]
cursor += HIDActionBase.mouse_resolution
x_index = np.argmax(x_ndarray)
x = (x_index / HIDActionBase.mouse_resolution) * max_x
del x_ndarray
del x_index
y_ndarray = ndarray[cursor : cursor + HIDActionBase.mouse_resolution]
cursor += HIDActionBase.mouse_resolution
y_index = np.argmax(y_ndarray)
y = (y_index / HIDActionBase.mouse_resolution) * max_y
del y_ndarray
del y_index
dx_ndarray = ndarray[cursor : cursor + HIDActionBase.mouse_resolution]
cursor += HIDActionBase.mouse_resolution
dx_index = np.argmax(dx_ndarray)
dx = (dx_index / HIDActionBase.mouse_resolution) * 2 * max_x - max_x
del dx_ndarray
del dx_index
dy_ndarray = ndarray[cursor : cursor + HIDActionBase.mouse_resolution]
cursor += HIDActionBase.mouse_resolution
dy_index = np.argmax(dy_ndarray)
dy = (dy_index / HIDActionBase.mouse_resolution) * 2 * max_y - max_y
del dy_ndarray
del dy_index
if action_type == "key_press":
construct_args.update(dict(key=key))
elif action_type == "key_release":
construct_args.update(dict(key=key))
elif action_type == "mouse_move":
construct_args.update(dict(x=x, y=y))
elif action_type == "mouse_click":
construct_args.update(
dict(
x=x, y=y, mouse_button=mouse_button, mouse_pressed=mouse_pressed
)
)
elif action_type == "mouse_scroll":
construct_args.update(dict(x=x, y=y, dx=dx, dy=dy))
else:
pass
del cursor
mHIDAction = HIDAction(**construct_args)
return mHIDAction
def round_within(self, number: Union[int, float], number_name: str) -> int:
result = round(number)
if result > self.mouse_resolution:
logger.warning(f"Warning: {number_name} overflow")
logger.warning(f"Value {result} greater than {self.mouse_resolution}")
return self.mouse_resolution
elif result < 0:
logger.warning(f"Warning: {number_name} overflow")
logger.warning(f"Value {result} smaller than 0")
return 0
return result
def to_ndarray(
self,
) -> np.ndarray:
action_type_ndarray = np.zeros((len(self.action_types), 1))
action_type_ndarray[self.action_types.index(self.action_type)] = 1
key_ndarray = np.zeros((len(self.keys), 1))
if self.key:
key_ndarray[self.keys.index(self.key)] = 1
mouse_button_ndarray = np.zeros((len(self.mouse_buttons), 1))
if self.mouse_button:
mouse_button_ndarray[self.mouse_buttons.index(self.mouse_button)] = 1
mouse_pressed_array = np.zeros((1, 1))
if self.mouse_pressed:
mouse_pressed_array[0] = 1
x_ndarray = np.zeros((self.mouse_resolution, 1))
if self.x:
x_ndarray[
self.round_within(self.mouse_resolution * self.x / self.max_x, "X")
] = 1
y_ndarray = np.zeros((self.mouse_resolution, 1))
if self.y:
y_ndarray[
self.round_within(self.mouse_resolution * self.y / self.max_y, "Y")
] = 1
dx_ndarray = np.zeros((self.mouse_resolution, 1))
if self.dx:
dx_ndarray[
self.round_within(
self.mouse_resolution * (self.dx + self.max_x) / (2 * self.max_x),
"DX",
)
] = 1
dy_ndarray = np.zeros((self.mouse_resolution, 1))
if self.dy:
dy_ndarray[
self.round_within(
self.mouse_resolution * (self.dy + self.max_y) / (2 * self.max_y),
"DY",
)
] = 1
ndarray = np.concatenate(
[
action_type_ndarray,
key_ndarray,
mouse_button_ndarray,
mouse_pressed_array,
x_ndarray,
y_ndarray,
dx_ndarray,
dy_ndarray,
]
)
return ndarray
def to_action_json(
self,
) -> Union[list, None]:
action_type = self.action_type
if action_type:
if action_type == "key_press":
assert self.key in self.keys
action_args = self.key
elif action_type == "key_release":
assert self.key in self.keys
action_args = self.key
elif action_type == "mouse_move":
assert self.x >= 0 and self.x <= self.max_x
assert self.y >= 0 and self.y <= self.max_y
action_args = [self.x, self.y]
elif action_type == "mouse_click":
assert self.x >= 0 and self.x <= self.max_x
assert self.y >= 0 and self.y <= self.max_y
assert self.mouse_button in self.mouse_buttons
assert type(self.mouse_pressed) == bool
action_args = [self.x, self.y, self.mouse_button, self.mouse_pressed]
elif action_type == "mouse_scroll":
assert self.x >= 0 and self.x <= self.max_x
assert self.y >= 0 and self.y <= self.max_y
assert self.dx >= -self.max_x and self.dx <= self.max_x
assert self.dy >= -self.max_y and self.dy <= self.max_y
action_args = [self.x, self.y, self.dx, self.dy]
else:
raise Exception("Unknown action_type: %s" % action_type)
action_json = [action_type, action_args]
else:
action_json = None
return action_json
#########################
# HID DATA VALIDATION #
#########################
from pydantic import confloat
class KeyPress(BaseModel):
_action_type = "key_press"
key: HIDActionTypes.keys
def to_list(self) -> List:
return [self._action_type, self.key]
@classmethod
def from_list(cls, lst: List):
action_type = lst[0]
action_args = [lst[1]]
assert len(action_args) == 1
assert action_type == cls._action_type
assert isinstance(action_args[0], HIDActionTypes.keys)
return cls(key=action_args[0])
class KeyRelease(BaseModel):
_action_type = "key_release"
key: HIDActionTypes.keys
def to_list(self) -> List:
return [self._action_type, self.key]
@classmethod
def from_list(cls, lst: List):
action_type = lst[0]
action_args = [lst[1]]
assert len(action_args) == 1
assert action_type == cls._action_type
assert isinstance(action_args[0], HIDActionTypes.keys)
return cls(key=action_args[0])
class MouseClick(BaseModel):
_action_type = "mouse_click"
x: confloat(ge=0)
y: confloat(ge=0)
button: HIDActionTypes.mouse_buttons
pressed: bool
def to_list(self) -> List:
return [self._action_type, [self.x, self.y, self.button, self.pressed]]
@classmethod
def from_list(cls, lst: List):
action_type = lst[0]
action_args = lst[1]
assert len(action_args) == 4
assert action_type == cls._action_type
assert isinstance(action_args[0], confloat(ge=0))
assert isinstance(action_args[1], confloat(ge=0))
assert isinstance(action_args[2], HIDActionTypes.mouse_buttons)
assert isinstance(action_args[3], bool)
return cls(
x=action_args[0],
y=action_args[1],
button=action_args[2],
pressed=action_args[3],
)
class MouseMove(BaseModel):
_action_type = "mouse_move"
x: confloat(ge=0)
y: confloat(ge=0)
def to_list(self) -> List:
return [self._action_type, [self.x, self.y]]
@classmethod
def from_list(cls, lst: List):
action_type = lst[0]
action_args = lst[1]
assert len(action_args) == 2
assert action_type == cls._action_type
assert isinstance(action_args[0], confloat(ge=0))
assert isinstance(action_args[1], confloat(ge=0))
return cls(x=action_args[0], y=action_args[1])
class MouseScroll(BaseModel):
_action_type = "mouse_scroll"
x: confloat(ge=0)
y: confloat(ge=0)
dx: float
dy: float
def to_list(self) -> List:
return [self._action_type, [self.x, self.y, self.dx, self.dy]]
@classmethod
def from_list(cls, lst: List):
action_type = lst[0]
action_args = lst[1]
assert len(action_args) == 4
assert action_type == cls._action_type
assert isinstance(action_args[0], confloat(ge=0))
assert isinstance(action_args[1], confloat(ge=0))
assert isinstance(action_args[2], float)
assert isinstance(action_args[3], float)
return cls(
x=action_args[0], y=action_args[1], dx=action_args[2], dy=action_args[3]
)
#################
# VIDEO CONTEXT #
#################
class VideoCaptureContextManager:
def __init__(self, videoPath):
self.videoPath = videoPath
def __enter__(self):
logger.info("Entering the context...")
self.cap = cv2.VideoCapture(self.videoPath)
return self.cap
def __exit__(self, exc_type, exc_value, exc_tb):
try:
self.cap.release()
finally:
import gc
gc.collect()
logger.info("Leaving the context...")
# print(exc_type, exc_value, exc_tb, sep="\n")
##################
# CONSCIOUS BASE #
##################
class ConsciousBase:
data_types = ["image", "HIDAction"]
special_tokens = ["image_newline", "image_end", "action_end", None]
# vector_size = 1+2+1000+4110 # visual things are pre-encoded. no raw image here!
# vector size is "length" now
image_dim = 224
image_channels = 3
data_type_length = len(data_types)
special_token_length = len(special_tokens)
image_length = image_dim * image_dim * image_channels # obviously flattened.
# FIX 1: plus to colon.
split_sizes = [
len(data_types),
len(special_tokens),
image_length, # FIX 9: change to flattened image bits count
HIDActionBase.length, # 4110?
]
length = sum(split_sizes)
# you cannot easily revert this compression by argmax or something else.
# so you need the decoder.
# can it be consciousnessless?
class ConsciousBlock(BaseModel, ConsciousBase):
data_type: Literal["image", "HIDAction"] # 2 bits, required
special_token: Union[
Literal[
"image_newline",
"image_end",
"action_end", # change some of these bits into -torch.inf, so you won't have paradox like results.
],
None,
] = None # 4 bits
image_data: Union[
None, NDArray
] = None # what is the shape of this image data? assume to be [3,224,224] (c h w) flattened
action_data: Union[None, NDArray] = None # assume to be: (4110, )
# [1,1000] -> [3,1000,1000] -> [3,224,224]
# einsum.repeat conv2d
# so, maybe you still need some ViT decode layer.
@staticmethod
def from_json(data: Mapping):
mConsciousBlock = ConsciousBlock(**data)
return mConsciousBlock
def to_json(self) -> Mapping:
mJson = self.dict()
return mJson
@staticmethod
def from_tensor(tensor: torch.Tensor):
# check its shape.
assert tensor.shape == (ConsciousBlock.length,)
split_sizes = ConsciousBase.split_sizes
data_bits, special_bits, image_data, action_data = einops.unpack(
tensor, [[s] for s in split_sizes], "*"
)
# data_bits, special_bits, image_data, action_data = size_splits(tensor, split_sizes)
data_type = ConsciousBase.data_types[int(torch.argmax(data_bits))]
if data_type == "image":
special_bits[2] = -torch.inf
special_token = ConsciousBase.special_tokens[
int(torch.argmax(special_bits))
]
mConsciousBlock = ConsciousBlock(
data_type=data_type, special_token=special_token, image_data=image_data
)
elif data_type == "HIDAction":
special_bits[0:2] = -torch.inf
special_token = ConsciousBase.special_tokens[
int(torch.argmax(special_bits))
]
mConsciousBlock = ConsciousBlock(
data_type=data_type,
special_token=special_token,
action_data=action_data,
)
else:
raise Exception("Unknown data_type:", data_type)
return mConsciousBlock
def to_tensor(self) -> torch.Tensor:
mTensorBase = torch.zeros((ConsciousBase.length))
# BUG 1: not enough values to unpack
# print(ConsciousBase.length)
# print(ConsciousBase.split_sizes)
data_bits, special_bits, image_data, action_data = einops.unpack(
mTensorBase, [[s] for s in ConsciousBase.split_sizes], "*"
)
# data_bits, special_bits, image_data, action_data = size_splits(mTensorBase, ConsciousBase.split_sizes)
data_bits[ConsciousBase.data_types.index(self.data_type)] = 1
if self.data_type == "image":
# BUG 2: comparing ndarray to None
# FIX 2: change "!=" into "is not"
assert self.image_data is not None
logger.debug("Image data shape: %s", self.image_data.shape)
logger.debug(
"Expected data shape: %s",
expected_data_shape := (ConsciousBase.image_length,),
)
assert self.image_data.shape == expected_data_shape
assert self.special_token != "action_end"
image_data = torch.Tensor(self.image_data)
special_bits[ConsciousBase.special_tokens.index(self.special_token)] = 1
elif self.data_type == "HIDAction":
assert self.action_data is not None
if len(self.action_data.shape) > 1:
self.action_data = self.action_data.reshape((-1,))
logger.debug("Action data shape: %s", self.action_data.shape)
# BUG: actual: (4110, 1)
# shall we reshape this.
logger.debug(
"Expected data shape: %s",
expected_data_shape := (HIDActionBase.length,),
) # TODO: expected shape is (4110, )? how to make this typed?
assert self.action_data.shape == expected_data_shape
assert self.special_token not in ["image_newline", "image_end"]
action_data = torch.Tensor(self.action_data)
special_bits[ConsciousBase.special_tokens.index(self.special_token)] = 1
else:
# FIX: found by pyright (UndefinedVariable)
raise Exception("Unknown data_type:", self.data_type)
mTensor, _ = einops.pack(
(data_bits, special_bits, image_data, action_data), "*"
)
# mTensor = torch.concat((data_bits, special_bits, image_data, action_data))
del mTensorBase
return mTensor
class ConsciousFlow(BaseModel, ConsciousBase):
consciousBlocks: List[ConsciousBlock]
@staticmethod
def from_json(data: List[Mapping]):
mList = [ConsciousBlock.from_json(j) for j in data]
mConsciousFlow = ConsciousFlow(consciousBlocks=mList)
return mConsciousFlow
def to_json(self) -> List[Mapping]:
mJson = [c.to_json() for c in self.consciousBlocks]
return mJson
@staticmethod
def from_tensor(tensor: torch.Tensor):
consciousBlockCount, vector_length = tensor.shape
assert vector_length == ConsciousBase.length
mConsciousBlocks = []
for i in range(consciousBlockCount):
arr = tensor[i, :] # dimension reduction.
mConsciousBlock = ConsciousBlock.from_tensor(arr)
mConsciousBlocks.append(mConsciousBlock)
mConsciousFlow = ConsciousFlow(consciousBlocks=mConsciousBlocks)
return mConsciousFlow
def to_tensor(self) -> torch.Tensor:
mTensor, _ = einops.pack([c.to_tensor() for c in self.consciousBlocks], "* d")
return mTensor
class ConsciousStream(BaseModel, ConsciousBase):
consciousFlows: List[ConsciousFlow]
@staticmethod
def from_json(data: List[Mapping]):
mList = [ConsciousFlow.from_json(j) for j in data]
mConsciousStream = ConsciousStream(consciousFlows=mList)
return mConsciousStream
def to_json(self) -> List[Mapping]:
mJson = [c.to_json() for c in self.consciousFlows]
return mJson
@staticmethod
def from_tensor(tensor: torch.Tensor):
consciousFlowCount, _, vector_length = tensor.shape
assert vector_length == ConsciousBase.length
mConsciousFlows = []
for i in range(consciousFlowCount):
arr = tensor[i, :, :] # dimension reduction.
mConsciousFlow = ConsciousFlow.from_tensor(arr)
mConsciousFlows.append(mConsciousFlow)
mConsciousStream = ConsciousStream(consciousFlows=mConsciousFlows)
return mConsciousStream
def to_tensor(self) -> torch.Tensor:
mTensor, _ = einops.pack([c.to_tensor() for c in self.consciousFlows], "* s d")
return mTensor
#####################
# TRAINER & DATASET #
#####################
class Trainer:
def __init__(self, model, loss_fn, optimizer):
self.model = model
self.loss_fn = loss_fn
self.optimizer = optimizer # shall be registered to model parameters.
def step(self, batched_input, batched_output=None):
# BUG 8: model forward keyword error
# FIX 8: fixing keyword, adding default keyword argument
model_output = self.model.forward(batched_input, target_output=batched_output)
loss = self.loss_fn(model_output, batched_output)
logger.debug("LOSS? %s", loss)
# this loss is incorrect. shall use some argmax stuff.
# to ensure that this thing is the thing that we want.
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
from typing import Protocol
class Enqueue(Protocol):
def enqueue(self, data, /):
...
def clear(self):
...
class TestEnqueue(Enqueue):
def __init__(self):
...
# self.queue = []
def enqueue(self, data):
logger.debug("DATA QUEUE: %s", data)
# may you print the data shape.
if data.action_data is not None:
logger.debug("ACTION DATA SHAPE: %s", data.action_data.shape)
elif data.image_data is not None:
logger.debug("IMAGE DATA SHAPE: %s", data.image_data.shape)
logger.debug("")
def clear(self):
...