-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgol_cpu.py
More file actions
executable file
·53 lines (42 loc) · 1.51 KB
/
Copy pathgol_cpu.py
File metadata and controls
executable file
·53 lines (42 loc) · 1.51 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
"""
Jeu de la Vie — Version CPU vectorisée (convolution 2D)
Usage :
python gol_cpu.py [H] [W] [steps]
python gol_cpu.py 512 512 100
"""
import torch
import torch.nn.functional as F
import time
import sys
# Kernel de Moore : 8 voisins, cellule centrale exclue
KERNEL = torch.tensor([[[[1., 1., 1.],
[1., 0., 1.],
[1., 1., 1.]]]])
def step(grid):
"""
Une génération du Jeu de la Vie.
grid : float32 (1, 1, H, W) avec valeurs 0.0 ou 1.0
"""
# Padding circulaire → grille toroïdale
padded = F.pad(grid, (1, 1, 1, 1), mode="circular")
neighbors = F.conv2d(padded, KERNEL)
alive = grid == 1.0
survive = alive & ((neighbors == 2) | (neighbors == 3))
born = ~alive & (neighbors == 3)
return (survive | born).float()
def run(H, W, steps, seed=42):
torch.manual_seed(seed)
grid = (torch.rand(1, 1, H, W) < 0.3).float()
print(f"Grille {H}×{W} | {steps} étapes | device : CPU")
print(f"Cellules vivantes initiales : {grid.sum():.0f}")
t0 = time.time()
for i in range(steps):
grid = step(grid)
elapsed = time.time() - t0
print(f"Cellules vivantes finales : {grid.sum():.0f}")
print(f"Temps total : {elapsed:.4f} s ({elapsed/steps*1000:.3f} ms/étape)")
if __name__ == "__main__":
H = int(sys.argv[1]) if len(sys.argv) > 1 else 512
W = int(sys.argv[2]) if len(sys.argv) > 2 else 512
steps = int(sys.argv[3]) if len(sys.argv) > 3 else 100
run(H, W, steps)