neroai14 commited on
Commit
d0fa06c
·
verified ·
1 Parent(s): 23b3ccc

Upload Empirical Evaluation of 4-bit Block-wise Quantization on Evolutionarily Developed Neural Networks.py

Browse files
Empirical Evaluation of 4-bit Block-wise Quantization on Evolutionarily Developed Neural Networks.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ # === 1. Genetic Engine and Environment (Chaos-Evolve V2) ===
4
+ class RobotBrainV2:
5
+ def __init__(self):
6
+ self.W1 = np.random.randn(4, 12) * 0.5
7
+ self.b1 = np.zeros((1, 12))
8
+ self.W2 = np.random.randn(12, 2) * 0.5
9
+ self.b2 = np.zeros((1, 2))
10
+ self.fitness = 0
11
+
12
+ def forward(self, X):
13
+ return np.dot(np.maximum(0, np.dot(X, self.W1) + self.b1), self.W2) + self.b2
14
+
15
+ def mutate(self, rate=0.35, scale=0.3):
16
+ if np.random.rand() < rate:
17
+ self.W1 += np.random.randn(*self.W1.shape) * scale
18
+ self.b1 += np.random.randn(*self.b1.shape) * scale
19
+ self.W2 += np.random.randn(*self.W2.shape) * scale
20
+ self.b2 += np.random.randn(*self.b2.shape) * scale
21
+
22
+
23
+ class ObstacleEnv:
24
+ def __init__(self): self.reset()
25
+
26
+ def reset(self):
27
+ self.agent_pos = np.random.uniform(-9, -5, (1, 2))
28
+ self.target_pos = np.random.uniform(5, 9, (1, 2))
29
+ self.obstacle_pos = np.array([[0.0, np.random.uniform(-4, 4)]])
30
+ self.steps_taken = 0
31
+ return self.get_state()
32
+
33
+ def get_state(self):
34
+ return np.hstack((self.target_pos - self.agent_pos, self.obstacle_pos - self.agent_pos))
35
+
36
+ def step(self, action):
37
+ move = np.clip(action, -1.2, 1.2)
38
+ next_pos = self.agent_pos + move
39
+ hit_obstacle = False
40
+ if (self.agent_pos[0, 0] < 0 and next_pos[0, 0] >= 0) or (self.agent_pos[0, 0] > 0 and next_pos[0, 0] <= 0):
41
+ if abs(next_pos[0, 1] - self.obstacle_pos[0, 1]) < 3.0: hit_obstacle = True
42
+ if not hit_obstacle: self.agent_pos = next_pos
43
+ self.steps_taken += 1
44
+ distance = np.linalg.norm(self.target_pos - self.agent_pos)
45
+ if hit_obstacle: distance += 15.0
46
+ return self.get_state(), distance, self.steps_taken >= 50 or distance < 0.3
47
+
48
+
49
+ def evaluate_brain(brain, env, episodes=5):
50
+ total_generation_distance = 0
51
+ crossed_wall = False
52
+ for _ in range(episodes):
53
+ state = env.reset()
54
+ start_x = env.agent_pos[0, 0]
55
+ done, total_distance, steps = False, 0, 0
56
+ while not done:
57
+ state, distance, done = env.step(brain.forward(state))
58
+ total_distance += distance; steps += 1
59
+ if env.agent_pos[0, 0] > 0 and start_x < 0: crossed_wall = True
60
+ total_generation_distance += (total_distance / steps)
61
+ base_fitness = 1000.0 / ((total_generation_distance / episodes) + 0.001)
62
+ brain.fitness = base_fitness * 2.5 if crossed_wall else base_fitness
63
+ return brain.fitness
64
+
65
+
66
+ # === 2. Compression Engine (Nero-Quantizer Core) ===
67
+ class NeroQuantizerCore:
68
+ def __init__(self):
69
+ self.qmin, self.qmax = -8, 7
70
+
71
+ def quantize_tensor(self, W, block_size=4):
72
+ """Compress a single weight matrix of the genetic champion using Block-wise quantization."""
73
+ orig_shape = W.shape
74
+ W_flat = W.flatten()
75
+
76
+ # Pad if the size is not aligned with the block size
77
+ remainder = len(W_flat) % block_size
78
+ if remainder != 0:
79
+ padding = block_size - remainder
80
+ W_flat = np.concatenate([W_flat, np.zeros(padding)])
81
+ else:
82
+ padding = 0
83
+
84
+ num_blocks = len(W_flat) // block_size
85
+ W_blocks = W_flat.reshape(num_blocks, block_size)
86
+
87
+ b_min = np.min(W_blocks, axis=1, keepdims=True)
88
+ b_max = np.max(W_blocks, axis=1, keepdims=True)
89
+
90
+ scales = (b_max - b_min) / (self.qmax - self.qmin)
91
+ scales = np.where(scales == 0, 1.0, scales)
92
+
93
+ zero_points = np.round(-b_min / scales) + self.qmin
94
+ zero_points = np.clip(zero_points, self.qmin, self.qmax).astype(np.int8)
95
+
96
+ q_blocks = np.round(W_blocks / scales) + zero_points
97
+ q_blocks = np.clip(q_blocks, self.qmin, self.qmax).astype(np.int8)
98
+
99
+ # Immediately dequantize for simulation
100
+ dq_blocks = (q_blocks.astype(np.float32) - zero_points) * scales
101
+ dq_flat = dq_blocks.flatten()
102
+
103
+ if padding > 0:
104
+ dq_flat = dq_flat[:-padding]
105
+
106
+ return dq_flat.reshape(orig_shape)
107
+
108
+
109
+ # === 3. Run the Experiment and Lab Integration ===
110
+ if __name__ == "__main__":
111
+ env = ObstacleEnv()
112
+ pop = [RobotBrainV2() for _ in range(120)]
113
+
114
+ print("Phase 1: Breeding the Genetic Overlord (100 Generations)...")
115
+ for g in range(1, 101):
116
+ for brain in pop: evaluate_brain(brain, env)
117
+ pop.sort(key=lambda x: x.fitness, reverse=True)
118
+ elites = pop[:18]
119
+ new_pop = list(elites)
120
+ while len(new_pop) < 120:
121
+ p1, p2 = np.random.choice(elites, size=2, replace=False)
122
+ alpha = np.random.rand()
123
+ child = RobotBrainV2()
124
+ child.W1 = alpha * p1.W1 + (1 - alpha) * p2.W1
125
+ child.W2 = alpha * p1.W2 + (1 - alpha) * p2.W2
126
+ child.mutate()
127
+ new_pop.append(child)
128
+ pop = new_pop
129
+
130
+ champion = pop[0]
131
+ fp32_fitness = evaluate_brain(champion, env)
132
+ print(f"-> FP32 Champion Fitness established: {fp32_fitness:.2f}")
133
+
134
+ print("\nPhase 2: Injecting Nero-Quantizer 4-bit Block-wise Compression...")
135
+ quantizer = NeroQuantizerCore()
136
+
137
+ # Clone the champion and compress each layer of its neural network independently
138
+ quantized_champion = RobotBrainV2()
139
+ quantized_champion.W1 = quantizer.quantize_tensor(champion.W1, block_size=4)
140
+ quantized_champion.b1 = quantizer.quantize_tensor(champion.b1, block_size=4)
141
+ quantized_champion.W2 = quantizer.quantize_tensor(champion.W2, block_size=4)
142
+ quantizer.b2 = quantizer.quantize_tensor(champion.b2, block_size=4)
143
+
144
+ # Evaluate the compressed champion's performance in the same challenging environment
145
+ int4_fitness = evaluate_brain(quantized_champion, env)
146
+ print(f"-> INT4 Quantized Champion Fitness established: {int4_fitness:.2f}")
147
+
148
+ # Calculate the intelligence retention rate
149
+ retention = (int4_fitness / fp32_fitness) * 100
150
+ print("\n" + "=" * 60)
151
+ print(f"FINAL REPORT: Quantization Robustness of Evolutionary Networks")
152
+ print("-" * 60)
153
+ print(f"FP32 Base Fitness : {fp32_fitness:.2f}")
154
+ print(f"INT4 Quant Fitness : {int4_fitness:.2f}")
155
+ print(f"Intelligence Retention Rate: {retention:.2f}%")
156
+ print("=" * 60)