-
Notifications
You must be signed in to change notification settings - Fork 0
/
QBOX_MAIN.py
1956 lines (1695 loc) · 70 KB
/
QBOX_MAIN.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
"""
## QBOX +1BIT
**Francisco Angulo de Lafuente**
**May 23, 2024**
https://github.com/Agnuxo1
**QBOX: Quantum-Inspired Box for Neural Network Exploration in Ray Tracing 3D Cube Environment**
QBOX is a pioneering platform designed to explore and enhance the capabilities of neural networks
through the integration of quantum-inspired computational models and ray tracing techniques within
a dynamic 3D cube environment. This innovative framework facilitates the development, training,
and deployment of advanced artificial intelligence algorithms, leveraging the unique features
of quantum mechanics to drive breakthroughs in computational efficiency, pattern recognition,
and predictive analysis.
By encapsulating complex neural structures in a virtual 'box,' QBOX offers researchers
a controlled environment to experiment with cutting-edge AI methodologies, fostering
the creation of next-generation solutions in areas such as computer vision,
graphics rendering, and data science.
**Abstract:**
This program simulates a 3D photonic neural processor designed to perform addition with two-bit numbers.
It leverages principles of Ray Tracing for efficient signal
propagation between photonic neurons, mimicking biological neural
communication. Each neuron operates on a +1-bit activation scheme, emitting
light pulses to transmit information.
The network utilizes a novel approach of neuronal collaboration, where
groups of neighboring neurons work together to achieve higher computational
precision, similar to having 2 or 3 bits of capacity. The processor is
organized into specialized areas to handle specific tasks, further
enhancing its efficiency.
The learning process employs principles of Hebbian learning, promoting biological plausibility and
energy efficiency. This project explores the potential of photonic
neural processors for developing energy-efficient, high-performance AI
systems, particularly suited for edge devices and resource-constrained
scenarios. This implementation uses CUDA for accelerated ray tracing calculations
on NVIDIA GPUs, drastically improving performance. The distance matrix calculation
is further optimized using shared memory for enhanced speed.
"""
import os # For file management
import time # For timekeeping
import math # For math functions such as sqrt
import numpy as np # Import NumPy for array handling
import cupy as cp # Import CuPy for GPU acceleration
import psutil # For system monitoring (CPU, Memory)
import GPUtil # For GPU monitoring
import random # For random number generation
import ray # For parallelization
from numba import cuda # For GPU acceleration and Ray Tracing
from deap import base, creator, tools, algorithms # For global parameter optimization
import threading
import CUBE_REPORT # Import the custom report module
from scipy.stats import entropy # For calculating information entropy
# --- Visualization Flag ---
Neuron_Activity = 0 # 0: Disabled, 1: Enabled
# --- Parameters ---
CUBE_SIZE = 2 # Cube size: 2x2x2
MAX_RAY_DISTANCE = 8 # Maximum distance a light ray can travel within the cube
ATTENUATION_FACTOR = 0.3 # Factor to reduce signal intensity over distance
FLASH_INTERVAL = 0.1 # Time interval between light pulses
NUM_PULSES = 4 # Number of pulses per flash
CARRIER_COUNT = 64 # Number of carriers for OFDM
FLASH_COUNT = 100 # Total number of flashes for training
TRAINING_FLASH_X = 1 # Number of processes for training flashes:
# 1: Traditional training (all neurons train together)
# 2: Two parallel training groups
# 3: Three parallel training groups
# 4: Four parallel training groups (by neuron class: Level1, Level2, Level3, Director+Communicators)
BIT_PRECISION = 2 # Bit precision for intensity and encoding
BATCH_SIZE = 16 # Batch size for batch normalization
OUTPUT_NEURON_COUNT = 2 # Number of output neurons (for binary encoding)
NEURON_COUNT = 99 # Neuron count: 1 Director + 3 Communicators + 94 other neurons + 1 Bias Neuron "ADJUST ACTIVE NEURON COUNT TO LEVELS"
LEVELS_X = 2 # Number of levels in the optical cube (0: only Director, 1, 2, 3... to infinity)
# --- Grid Parameters ---
GRID_DIMENSIONS = np.array([10, 10, 10]) # Dimensions of the spatial grid
CELL_SIZE = 1 # Size of each grid cell
MAX_NEIGHBORS_PER_CELL = 50 # Define the maximum number of neighbors a cell can have
# --- Neuron Parameters ---
MIN_OPACITY_THRESHOLD = 0.1 # Minimum threshold for opacity of the neuron
MAX_OPACITY_THRESHOLD = 0.7 # Maximum threshold for opacity of the neuron
MIN_REFLECTANCE = 0.1 # Minimum reflectance for the neuron
MAX_REFLECTANCE = 0.9 # Maximum reflectance for the neuron
MIN_EMISSION_INTENSITY = (
0.1 # Minimum emission ray intensity for the neuron
)
MAX_EMISSION_INTENSITY = (
0.9 # Maximum emission ray intensity for the neuron
)
MIN_INTENSITY_DECAY = 0.1 # Minimum intensity reflection decay for the neuron
MAX_INTENSITY_DECAY = 0.9 # Maximum intensity reflection decay for the neuron
MIN_LEARNING_RATE = 0.009 # Increased from 0.05
MAX_LEARNING_RATE = 0.05 # Increased from 0.1
MIN_REFLECTANCE_DECAY = 0.1
MAX_REFLECTANCE_DECAY = 0.9
NOISE_AMPLITUDE = 0.003 # Random luminosity noise amplitude
# --- Global Learning Parameters ---
RECURRENCE_FACTOR = 0.2 # Controls influence of previous intensity
INTENSITY_DECAY = 0.5 # Rate of intensity decay
REFLECTANCE_DECAY = 0.03 # Rate of reflectance decay
HEBBIAN_LEARNING_RATE = 0.001 # Learning rate for Hebbian learning
REWARD_RATE = 1 # Reward for correct responses (Increased from 0.1)
PENALTY_RATE = 0.1 # Penalty for incorrect responses
# --- Fine-Tuning Parameters ---
FINE_TUNE_FLASHES = 50 # Number of flashes to use during fine-tuning
FINE_TUNE_ITERATIONS = 3 # Number of fine-tuning iterations
FINE_TUNE_STEP_SIZE = 0.05 # Step size for parameter adjustments
AUTO_FINE_TUNING_X = 0 # Number of processes for fine-tuning (0: disabled, >1: enabled)
# --- Association Parameters ---
ASSOCIATION_EVALUATION_INTERVAL = 10 # Evaluate association every 10 iterations
TARGET_PRECISION = 8 # Desired precision in bits for associations
ENTROPY_THRESHOLD = 1.0 # Entropy threshold for dissolving associations
# --- Watchdog Parameters ---
WATCHDOG_INTENSITY = 0 # Intensity level of the watchdog (0: disabled, 1-9: increasing intensity)
WATCHDOG_CHECK_DURATION = 5 # Duration (in seconds) for the watchdog to perform checks
WATCHDOG_REST_DURATION = 5 # Duration (in seconds) for the watchdog to rest between checks
# Import CUBE_REPORT (handle ImportError if module not found)
try:
import CUBE_REPORT
except ImportError:
print(
"Warning: CUBE_REPORT module not found. Reporting functionality will be limited."
)
# --- Grid Class ---
class Grid:
"""
Represents the spatial grid used for efficient neighbor search during ray tracing.
Attributes:
dimensions (numpy.array): Dimensions of the grid in 3D space.
cell_size (float): Size of each cell in the grid.
grid (dict): Dictionary storing neuron indices in each cell. Key is the cell index,
and value is a list of neuron indices.
"""
def __init__(self, dimensions, cell_size):
self.dimensions = dimensions
self.cell_size = cell_size
self.grid = {}
def _get_cell_index(self, position):
"""
Calculates the index of the grid cell based on a given position.
Args:
position (numpy.array): The 3D coordinates (x, y, z) of a point.
Returns:
tuple: A tuple representing the (x, y, z) index of the grid cell containing the point.
"""
return tuple((position // self.cell_size).astype(int))
def add_neuron(self, neuron, index):
"""
Adds a neuron to the corresponding grid cell based on its position.
Args:
neuron (Neuron): The Neuron object to add to the grid.
index (int): The index of the neuron in the neural_cube_data list.
"""
position = np.array([neuron.x, neuron.y, neuron.z])
cell_index = self._get_cell_index(position)
if cell_index not in self.grid:
self.grid[cell_index] = []
self.grid[cell_index].append(index) # Add the neuron's index to the grid cell
def get_neighbors(self, neuron, neurons):
"""
Retrieves neighboring neurons of a given neuron from the grid.
Args:
neuron (Neuron): The neuron for which to find neighbors.
neurons (list): The list of all neurons in the cube.
Returns:
list: A list of Neuron objects that are neighbors of the given neuron.
"""
position = np.array([neuron.x, neuron.y, neuron.z])
cell_index = self._get_cell_index(position)
neighbors = []
for i in range(-1, 2):
for j in range(-1, 2):
for k in range(-1, 2):
neighboring_cell = (
cell_index[0] + i,
cell_index[1] + j,
cell_index[2] + k,
)
if neighboring_cell in self.grid:
neighbors.extend(self.grid[neighboring_cell])
return [
neurons[i] for i in neighbors
] # Return the actual Neuron objects based on their indices
# --- Neuron Classes ---
class Neuron:
"""
Represents a neuron in the optical cube.
Attributes:
name (str): Unique name of the neuron.
x (float): x-coordinate of the neuron in the cube.
y (float): y-coordinate of the neuron in the cube.
z (float): z-coordinate of the neuron in the cube.
neuron_type (str): Type of neuron ('Director', 'Communicator', 'Level1', 'Level2', 'Level3', 'Output', 'Bias').
opacity_threshold (float): Light intensity threshold for the neuron to become active.
received_intensity (float): Current light intensity received by the neuron.
previous_intensity (float): Light intensity received in the previous timestep.
active (bool): True if the neuron is currently active, False otherwise.
reflectance (float): Proportion of light the neuron reflects.
emission_intensity (float): Intensity of light emitted when the neuron is active.
intensity_decay (float): Rate at which received light intensity decays over time.
learning_rate (float): Learning rate for adjusting reflectance.
reflectance_decay (float): Rate at which reflectance decays over time.
memory (int): Not used currently, placeholder for future implementations.
bias (float): Bias value added to the received intensity.
precision (int): Current precision of the neuron in bits (initial precision is set to 2).
associated_neurons (list): List of neurons associated with this neuron.
meta_neuron (MetaNeuron): Reference to the MetaNeuron if this neuron is part of an association.
"""
def __init__(
self,
name,
x,
y,
z,
neuron_type,
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias=0.0,
initial_precision=2,
):
self.name = name
self.x = x
self.y = y
self.z = z
self.neuron_type = neuron_type
self.opacity_threshold = opacity_threshold
self.received_intensity = 0.0
self.previous_intensity = 0.0
self.active = False
self.reflectance = reflectance
self.emission_intensity = emission_intensity
self.intensity_decay = intensity_decay
self.learning_rate = random.uniform(MIN_LEARNING_RATE, MAX_LEARNING_RATE)
self.reflectance_decay = random.uniform(
MIN_REFLECTANCE_DECAY, MAX_REFLECTANCE_DECAY
)
self.memory = 3
self.bias = bias
self.precision = initial_precision
self.associated_neurons = []
self.meta_neuron = None
def __repr__(self):
return f"{self.name} ({self.x}, {self.y}, {self.z}, {self.opacity_threshold:.2f}, {self.received_intensity:.2f}, {self.active}, {self.reflectance:.2f})"
def sigmoid(self, x):
"""Sigmoid activation function (currently not used)."""
return 1 / (1 + np.exp(-x))
def leaky_relu(self, x, alpha=0.01):
"""Leaky ReLU activation function."""
return max(alpha * x, x)
def he_initialization(self):
"""He initialization for reflectance (currently not used)."""
return random.gauss(0, math.sqrt(2 / NEURON_COUNT))
def update_activation(self):
"""Activates the neuron if received intensity exceeds the opacity threshold."""
self.active = (
self.leaky_relu(self.received_intensity - self.opacity_threshold) > 0
)
def limit_intensity(self):
"""Limits the received intensity to a reasonable range."""
self.received_intensity = min(max(self.received_intensity, -10), 10)
def adjust_reflectance(self, delta):
"""Adjusts the reflectance based on learning."""
self.reflectance += self.learning_rate * delta
self.reflectance = max(-2, min(self.reflectance, 2))
def apply_reflectance_decay(self):
"""Applies reflectance decay over time."""
self.reflectance *= 1 - self.reflectance_decay
def update_intensity(self, neural_cube_intensity, i, dampening_factor=0.9):
"""Updates the received intensity based on propagation and other factors."""
self.previous_intensity = self.received_intensity
self.received_intensity = (
0.8 * self.previous_intensity
+ 0.2
* (
neural_cube_intensity[i]
+ (self.emission_intensity * self.reflectance if self.active else 0)
)
)
self.received_intensity += self.bias + np.random.normal(0, 0.05)
self.received_intensity *= dampening_factor
self.received_intensity = min(max(self.received_intensity, -10), 10)
self.update_activation()
# Define specialized neuron classes (empty for now - inherit from Neuron)
class Director(Neuron):
"""Represents the Director neuron at the core of the cube."""
def __init__(
self,
name,
x,
y,
z,
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias=0.0,
):
super().__init__(
name,
x,
y,
z,
"Director",
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias,
)
class Communicator(Neuron):
"""Represents a Communicator neuron that connects different levels."""
def __init__(
self,
name,
x,
y,
z,
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias=0.0,
):
super().__init__(
name,
x,
y,
z,
"Communicator",
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias,
)
class Level1(Neuron):
"""Represents a neuron in Level 1 of the cube."""
def __init__(
self,
name,
x,
y,
z,
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias=0.0,
):
super().__init__(
name,
x,
y,
z,
"Level1",
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias,
)
class Level2(Neuron):
"""Represents a neuron in Level 2 of the cube."""
def __init__(
self,
name,
x,
y,
z,
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias=0.0,
):
super().__init__(
name,
x,
y,
z,
"Level2",
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias,
)
class Level3(Neuron):
"""Represents a neuron in Level 3 of the cube."""
def __init__(
self,
name,
x,
y,
z,
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias=0.0,
):
super().__init__(
name,
x,
y,
z,
"Level3",
opacity_threshold,
emission_intensity,
intensity_decay,
reflectance,
bias,
)
class MetaNeuron:
"""
Represents a group of associated neurons acting as a single unit.
Attributes:
neurons (list): List of Neuron objects that are part of this association.
precision (int): Total precision of the MetaNeuron in bits, calculated as the sum of precisions of its constituent neurons.
"""
def __init__(self, neurons):
self.neurons = neurons
self.precision = sum([n.precision for n in neurons])
# ... (Methods for calculations with increased precision will be added here) ...
# --- Batch Normalization ---
class BatchNorm:
"""
Implements batch normalization to stabilize and accelerate training.
"""
def __init__(self, num_features, eps=1e-5, momentum=0.1):
self.eps = eps
self.momentum = momentum
self.gamma = np.ones(num_features)
self.beta = np.zeros(num_features)
self.running_mean = np.zeros(num_features)
self.running_var = np.ones(num_features)
def forward(self, x, training=True):
if training:
batch_mean = np.mean(x, axis=0)
batch_var = np.var(x, axis=0)
self.running_mean = (
self.momentum * batch_mean + (1 - self.momentum) * self.running_mean
)
self.running_var = (
self.momentum * batch_var + (1 - self.momentum) * self.running_var
)
x_hat = (x - batch_mean) / np.sqrt(batch_var + self.eps)
else:
x_hat = (x - self.running_mean) / np.sqrt(self.running_var + self.eps)
return self.gamma * x_hat + self.beta
# --- Quantization Function ---
def quantize(value, bits=BIT_PRECISION):
"""
Quantizes a value to a given number of bits.
"""
max_value = 2**bits - 1
return round(value * max_value) / max_value
# --- Neural Cube Initialization ---
def initialize_neural_cube(grid):
"""
Initializes the optical cube with neurons arranged in a 3D grid,
following a Matryoshka doll structure (expanding cubes for each level).
Also adds the neurons to the spatial grid.
Args:
grid (Grid): The spatial grid to add the neurons to.
Returns:
list: List of neurons in the cube.
"""
neural_cube_data = []
neuron_id = 1 # Unique ID for each neuron, starting with the Director (1)
grid_size = 1 # Initial size of the grid (for level 0)
for level in range(LEVELS_X + 1):
# 3D Grid: Not actually used, could be removed.
grid_np = np.zeros((grid_size, grid_size, grid_size), dtype=int)
distance_between_neurons = 1 / grid_size # Distance between neurons
# Traverse the grid to place the neurons
for i in range(grid_size):
for j in range(grid_size):
for k in range(grid_size):
# Avoid the center in higher levels (occupied by inner cubes)
if (
level == 0
or (i != grid_size // 2 or j != grid_size // 2)
or k != grid_size // 2
):
x = (i + 0.5) * distance_between_neurons
y = (j + 0.5) * distance_between_neurons
z = (k + 0.5) * distance_between_neurons
# Neuron type assignment based on level and position
if neuron_id == 1:
neuron_type = "Director"
elif i == 0 and j == 0 and k == 0:
neuron_type = "Communicator"
else:
neuron_type = f"Level{level}"
# Create the neuron
neuron = globals()[neuron_type](
f"{neuron_type}-{neuron_id}",
x,
y,
z,
random.uniform(
MIN_OPACITY_THRESHOLD, MAX_OPACITY_THRESHOLD
),
random.uniform(
MIN_EMISSION_INTENSITY, MAX_EMISSION_INTENSITY
),
random.uniform(MIN_INTENSITY_DECAY, MAX_INTENSITY_DECAY),
random.uniform(MIN_REFLECTANCE, MAX_REFLECTANCE),
random.uniform(0.1, 0.3),
)
neural_cube_data.append(neuron)
grid.add_neuron(
neuron, len(neural_cube_data) - 1
) # Add the neuron to the grid using its index
neuron_id += 1
grid_size *= 2 # Expand the grid for the next level (like a Matryoshka doll)
# Output neurons
output_spacing = (
1 / OUTPUT_NEURON_COUNT
) # Space between output neurons
for i in range(OUTPUT_NEURON_COUNT):
x = (i + 0.5) * output_spacing
neuron = Neuron(
f"Output-{i+1}",
x,
0,
0,
"Output",
quantize(random.uniform(MIN_OPACITY_THRESHOLD, MAX_OPACITY_THRESHOLD)),
quantize(random.uniform(MIN_EMISSION_INTENSITY, MAX_EMISSION_INTENSITY)),
quantize(random.uniform(MIN_INTENSITY_DECAY, MAX_INTENSITY_DECAY)),
quantize(random.uniform(MIN_REFLECTANCE, MAX_REFLECTANCE)),
quantize(random.uniform(0.1, 0.3)),
)
neural_cube_data.append(neuron)
grid.add_neuron(
neuron, len(neural_cube_data) - 1
) # Add output neuron to the grid
# --- Bias Neuron ---
neural_cube_data.append(
Neuron("Bias", 0, 0, 0, "Bias", 0, 0, 0, 1.0, 0)
) # Add bias neuron, intensity always = 1, not trainable
grid.add_neuron(
neural_cube_data[-1], len(neural_cube_data) - 1
) # Add bias neuron to the grid
return neural_cube_data
# --- Neuron Group Definition ---
# Grouping is done dynamically based on neuron type, no need to hardcode indices
def get_neuron_groups(neural_cube_data):
"""
Groups neurons based on their types. This is used for analysis and training.
"""
return [
[n for n in neural_cube_data if n.neuron_type == "Level1"],
[n for n in neural_cube_data if n.neuron_type == "Level2"],
[n for n in neural_cube_data if n.neuron_type == "Level3"],
[n for n in neural_cube_data if n.neuron_type in ["Director", "Communicator"]], # Group Director + Communicators
]
# --- Initialize batch normalization ---
# Assuming you want to normalize intensities for all trainable neurons
def initialize_batch_norm(neural_cube_data):
"""
Initializes the batch normalization layer for the network.
"""
trainable_neurons = [n for n in neural_cube_data if n.neuron_type != "Bias"]
return BatchNorm(len(trainable_neurons))
# Initial reflectances
group_reflectances = [1.0, 1.0, 1.0, 1.0]
# --- Optical Path Matrix Calculation (CUDA) ---
@cuda.jit(device=True)
def calculate_distance_gpu(x1, y1, z1, x2, y2, z2):
"""Calculates the Euclidean distance between two points in 3D space (for GPU)."""
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2)
def calculate_distance(x1, y1, z1, x2, y2, z2):
"""Calculates the Euclidean distance between two points in 3D space (for CPU)."""
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2)
@cuda.jit
def calculate_optical_path_matrix_kernel(neuron_count, neurons, optical_path_matrix):
"""
CUDA kernel to calculate the optical path matrix, representing distances between neurons.
"""
i, j = cuda.grid(2)
if i < neuron_count and j < neuron_count:
n1 = neurons[i]
n2 = neurons[j]
optical_path_matrix[i, j] = calculate_distance_gpu(
n1[0], n1[1], n1[2], n2[0], n2[1], n2[2]
)
def calculate_optical_path_matrix(neurons):
"""
Calculates the optical path matrix using GPU acceleration (CUDA).
The matrix represents the distances between each pair of neurons in the cube.
"""
neuron_count = len(neurons)
# Initialize the matrix on the GPU using CuPy
optical_path_matrix = cp.zeros((neuron_count, neuron_count), dtype=cp.float32)
# Create the neuron array on the GPU using CuPy
neurons_flat = cp.array([(n.x, n.y, n.z) for n in neurons], dtype=cp.float32)
# Adjust grid and block dimensions for optimal GPU utilization
threads_per_block = (
16,
16,
) # Experiment with higher values (multiples of 32)
blocks_per_grid_x = (
neuron_count + threads_per_block[0] - 1
) // threads_per_block[0]
blocks_per_grid_y = (
neuron_count + threads_per_block[1] - 1
) // threads_per_block[1]
blocks_per_grid = (blocks_per_grid_x, blocks_per_grid_y)
# Launch the CUDA kernel
calculate_optical_path_matrix_kernel[blocks_per_grid, threads_per_block](
neuron_count, neurons_flat, optical_path_matrix
)
# Synchronize to ensure calculations are finished and return the matrix
cp.cuda.Stream.null.synchronize()
return optical_path_matrix
# --- Light Propagation (CUDA) ---
@cuda.jit
def propagate_light_kernel(
neural_cube_intensity,
neuron_positions,
reflectances,
max_distance,
grid_gpu,
grid_shape,
cell_size,
):
"""
CUDA kernel for light propagation from each neuron to its neighbors using the spatial grid.
"""
idx = cuda.grid(1)
if idx < neuron_positions.shape[0]:
x1, y1, z1 = neuron_positions[idx]
cell_index_x = int(x1 // cell_size)
cell_index_y = int(y1 // cell_size)
cell_index_z = int(z1 // cell_size)
# Iterate over neighboring cells
for i in range(-1, 2):
for j in range(-1, 2):
for k in range(-1, 2):
neighboring_cell_x = cell_index_x + i
neighboring_cell_y = cell_index_y + j
neighboring_cell_z = cell_index_z + k
# Check if the neighboring cell is within the grid bounds
if (
0 <= neighboring_cell_x < grid_shape[0]
and 0 <= neighboring_cell_y < grid_shape[1]
and 0 <= neighboring_cell_z < grid_shape[2]
):
# Calculate the flattened index of the neighboring cell
cell_index = (
neighboring_cell_x * grid_shape[1] * grid_shape[2]
+ neighboring_cell_y * grid_shape[2]
+ neighboring_cell_z
)
neighbors = grid_gpu[cell_index]
# Iterate over neurons in the neighboring cell
for n in neighbors:
if n == -1:
break
if (
idx != n
): # Don't propagate light to itself
x2, y2, z2 = neuron_positions[n]
distance = (
(x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2
) ** 0.5
if distance < max_distance:
intensity = reflectances[idx] / (distance**2)
cuda.atomic.add(
neural_cube_intensity, n, intensity
)
def propagate_light_gpu(neurons, grid, max_distance):
"""
Simulates light propagation from each neuron to its neighbors using the GPU and the spatial grid.
Args:
neurons (list): List of neurons.
grid (Grid): The spatial grid containing the neurons.
max_distance (float): Maximum light propagation distance.
"""
neuron_positions = cp.array(
[[n.x, n.y, n.z] for n in neurons], dtype=cp.float32
)
reflectances = cp.array([n.reflectance for n in neurons], dtype=cp.float32)
neural_cube_intensity = cp.zeros(len(neurons), dtype=cp.float32)
grid_shape = grid.dimensions // grid.cell_size
# 1. Calcular el número máximo de vecinos por celda
max_neighbors = max(
[len(cell_neurons) for cell_neurons in grid.grid.values()]
)
# 2. Crear un array 2D en la GPU para almacenar los índices de neuronas
grid_gpu = cp.full(
(grid_shape[0] * grid_shape[1] * grid_shape[2], max_neighbors),
-1,
dtype=cp.int32,
)
# 3. Llenar grid_gpu con los índices de neuronas
for cell_index, cell_neurons in grid.grid.items():
flat_index = (
cell_index[0] * grid_shape[1] * grid_shape[2]
+ cell_index[1] * grid_shape[2]
+ cell_index[2]
)
grid_gpu[flat_index, : len(cell_neurons)] = cp.array(
cell_neurons, dtype=cp.int32
)
# 4. Ajustar las dimensiones del kernel
threads_per_block = 256 # Ajuste basado en la arquitectura de la GPU
blocks_per_grid = (
len(neuron_positions) + threads_per_block - 1
) // threads_per_block
# 5. Lanzar el kernel CUDA
propagate_light_kernel[blocks_per_grid, threads_per_block](
neural_cube_intensity,
neuron_positions,
reflectances,
max_distance,
grid_gpu,
grid_shape,
grid.cell_size,
)
# Update neuron intensities
for i, neuron in enumerate(neurons):
if neuron.neuron_type != "Bias":
neuron.received_intensity += neural_cube_intensity[i].get()
neuron.received_intensity = min(
max(neuron.received_intensity, -10), 10
)
neuron.received_intensity = quantize(neuron.received_intensity)
neuron.update_activation()
all_neurons_in_groups = [
n for group in get_neuron_groups(neurons) for n in group
]
normalize_intensity(all_neurons_in_groups, eps=1e-8)
# --- OFDM Encoding and Decoding ---
def ofdm_modulate(data, carrier_count=CARRIER_COUNT):
"""
Modulate data using OFDM.
Args:
data (np.ndarray): The data to modulate.
carrier_count (int): Number of carriers.
Returns:
np.ndarray: The OFDM modulated signal.
"""
symbols = np.fft.ifft(data, carrier_count)
return np.concatenate([symbols[-carrier_count // 4 :], symbols])
def ofdm_demodulate(signal, carrier_count=CARRIER_COUNT):
"""
Demodulate OFDM signal.
Args:
signal (np.ndarray): The OFDM signal to demodulate.
carrier_count (int): Number of carriers.
Returns:
np.ndarray: The demodulated data.
"""
symbols = signal[carrier_count // 4 : carrier_count // 4 + carrier_count]
return np.fft.fft(symbols, carrier_count)
def generate_data_sequence(number, bit_length=CARRIER_COUNT):
"""
Generates a binary sequence representing a number.
Args:
number (int): The number to encode.
bit_length (int): The length of the bit sequence.
Returns:
np.ndarray: The binary sequence.
"""
return np.array([int(bit) for bit in format(number, f"0{bit_length}b")], dtype=np.float64)
def decode_data_sequence(sequence):
"""
Decodes a binary sequence to retrieve the original number.
Args:
sequence (np.ndarray): The binary sequence.
Returns:
int: The decoded number.
"""
return int("".join(map(str, sequence.astype(int))), 2)
def transmit_data(data, carrier_count=CARRIER_COUNT):
"""
Transmit data using OFDM.
Args:
data (int): The data to transmit.
carrier_count (int): Number of carriers.
"""
data_sequence = generate_data_sequence(data, carrier_count)
ofdm_signal = ofdm_modulate(data_sequence, carrier_count)
# Transmit ofdm_signal to the neural cube (implementation depends on your system)
return ofdm_signal
def receive_data(ofdm_signal, carrier_count=CARRIER_COUNT):
"""
Receive data using OFDM.
Args:
ofdm_signal (np.ndarray): The OFDM signal received.
carrier_count (int): Number of carriers.
Returns:
int: The received data.
"""
demodulated_data = ofdm_demodulate(ofdm_signal, carrier_count)
demodulated_sequence = (np.real(demodulated_data) > 0).astype(np.float32)
return decode_data_sequence(demodulated_sequence)
# --- Neuron Association Functions ---
def find_neighbors(neuron, neural_cube_data, max_distance=1):
"""
Finds neighboring neurons within a specified maximum distance.
"""
neighbors = []
for other_neuron in neural_cube_data:
if other_neuron != neuron and calculate_distance(
neuron.x,
neuron.y,
neuron.z,
other_neuron.x,
other_neuron.y,
other_neuron.z,
) <= max_distance:
neighbors.append(other_neuron)
return neighbors
def calculate_entropy(neurons, parameter="reflectance"):
"""
Calculates the Shannon entropy of a given parameter within a group of neurons.
Entropy is a measure of information or uncertainty. Higher entropy implies more variability or information content.
"""
values = [getattr(n, parameter) for n in neurons]
probabilities = (
np.histogram(values, bins=2 ** max([n.precision for n in neurons]))[0]
/ len(neurons)
)
return entropy(probabilities)
def evaluate_association(
neuron, neighbors, target_precision, current_accuracy, cost_function
):
"""
Evaluates the potential benefit of neuron association.
It checks different group sizes of neighboring neurons to find the group that
provides the maximum benefit (improvement in accuracy minus the cost of association).
"""
best_group = []
best_benefit = 0
for group_size in range(1, len(neighbors) + 1):
group = neighbors[:group_size]
group_precision = sum([n.precision for n in group])
if group_precision >= target_precision:
association_cost = cost_function(group)
potential_accuracy = estimate_accuracy_improvement(
group, current_accuracy
)
benefit = potential_accuracy - association_cost
if benefit > best_benefit: