unipram 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. unipram-0.1.0/.gitignore +20 -0
  2. unipram-0.1.0/LICENSE +21 -0
  3. unipram-0.1.0/PKG-INFO +146 -0
  4. unipram-0.1.0/README.md +99 -0
  5. unipram-0.1.0/docs/css/unipram.css +5 -0
  6. unipram-0.1.0/docs/etendre.md +95 -0
  7. unipram-0.1.0/docs/index.md +67 -0
  8. unipram-0.1.0/docs/machines.md +107 -0
  9. unipram-0.1.0/docs/observer.md +98 -0
  10. unipram-0.1.0/docs/programme.md +132 -0
  11. unipram-0.1.0/docs/reference.md +73 -0
  12. unipram-0.1.0/docs/verifier.md +96 -0
  13. unipram-0.1.0/mkdocs.yml +77 -0
  14. unipram-0.1.0/pyproject.toml +76 -0
  15. unipram-0.1.0/src/unipram/__init__.py +77 -0
  16. unipram-0.1.0/src/unipram/_codegen.py +27 -0
  17. unipram-0.1.0/src/unipram/accesses.py +148 -0
  18. unipram-0.1.0/src/unipram/gpu.py +115 -0
  19. unipram-0.1.0/src/unipram/instruction.py +134 -0
  20. unipram-0.1.0/src/unipram/machine.py +210 -0
  21. unipram-0.1.0/src/unipram/machines.py +30 -0
  22. unipram-0.1.0/src/unipram/model.py +48 -0
  23. unipram-0.1.0/src/unipram/observers.py +145 -0
  24. unipram-0.1.0/src/unipram/py.typed +0 -0
  25. unipram-0.1.0/src/unipram/simulated.py +102 -0
  26. unipram-0.1.0/src/unipram/synchronous.py +186 -0
  27. unipram-0.1.0/src/unipram/threaded.py +109 -0
  28. unipram-0.1.0/src/unipram/trace.py +132 -0
  29. unipram-0.1.0/src/unipram/writes.py +61 -0
  30. unipram-0.1.0/templates/python/material/languages/fr.html.jinja +15 -0
  31. unipram-0.1.0/tests/conftest.py +46 -0
  32. unipram-0.1.0/tests/functional/test_docs.py +37 -0
  33. unipram-0.1.0/tests/functional/test_readme.py +30 -0
  34. unipram-0.1.0/tests/integration/test_factories.py +44 -0
  35. unipram-0.1.0/tests/integration/test_machine_contract.py +247 -0
  36. unipram-0.1.0/tests/integration/test_simulator_errors.py +41 -0
  37. unipram-0.1.0/tests/seul.py +52 -0
  38. unipram-0.1.0/tests/unit/test_accesses.py +123 -0
  39. unipram-0.1.0/tests/unit/test_instruction.py +136 -0
  40. unipram-0.1.0/tests/unit/test_model.py +23 -0
  41. unipram-0.1.0/tests/unit/test_observers.py +82 -0
  42. unipram-0.1.0/tests/unit/test_synchronous.py +82 -0
  43. unipram-0.1.0/tests/unit/test_trace.py +133 -0
  44. unipram-0.1.0/tests/unit/test_writes.py +30 -0
@@ -0,0 +1,20 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ .coverage
8
+ htmlcov/
9
+ dist/
10
+ build/
11
+ *.egg-info/
12
+ .DS_Store
13
+ *.doc
14
+ *.docx
15
+ *.ppt
16
+ *.pptx
17
+ *.xls
18
+ *.xlsx
19
+ correction/
20
+ site/
unipram-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lilian Aveneau
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
unipram-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.5
2
+ Name: unipram
3
+ Version: 0.1.0
4
+ Summary: Write PRAM algorithms once; check them on a simulator, run them on threads or a GPU
5
+ Project-URL: Documentation, https://laveneau.github.io/unipram/
6
+ Project-URL: Source, https://github.com/laveneau/unipram
7
+ Project-URL: Issues, https://github.com/laveneau/unipram/issues
8
+ Author: Lilian Aveneau
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: GPU,PRAM,parallel algorithms,simulator,teaching
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: Natural Language :: French
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Classifier: Topic :: Education
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.12
25
+ Requires-Dist: numpy>=2.0
26
+ Provides-Extra: cuda
27
+ Requires-Dist: unigpu[cuda]>=0.3; extra == 'cuda'
28
+ Provides-Extra: cuda13
29
+ Requires-Dist: unigpu[cuda13]>=0.4; extra == 'cuda13'
30
+ Provides-Extra: docs
31
+ Requires-Dist: mkdocs-material>=9.6; extra == 'docs'
32
+ Requires-Dist: mkdocs<2,>=1.6; extra == 'docs'
33
+ Requires-Dist: mkdocstrings[python]>=0.29; extra == 'docs'
34
+ Provides-Extra: gpu
35
+ Requires-Dist: unigpu>=0.3; extra == 'gpu'
36
+ Provides-Extra: metal
37
+ Requires-Dist: unigpu[metal]>=0.3; extra == 'metal'
38
+ Provides-Extra: opencl
39
+ Requires-Dist: unigpu[opencl]>=0.3; extra == 'opencl'
40
+ Provides-Extra: test
41
+ Requires-Dist: mypy>=1.15; extra == 'test'
42
+ Requires-Dist: pytest-cov>=5; extra == 'test'
43
+ Requires-Dist: pytest>=8; extra == 'test'
44
+ Requires-Dist: ruff>=0.9; extra == 'test'
45
+ Requires-Dist: unigpu>=0.3; extra == 'test'
46
+ Description-Content-Type: text/markdown
47
+
48
+ # unipram: write a PRAM algorithm once, check it, run it anywhere
49
+
50
+ `unipram` is made to **teach parallel algorithms**. A PRAM algorithm is written
51
+ once, in plain Python. The same code then runs on three machines:
52
+
53
+ | Machine | What it does |
54
+ |---|---|
55
+ | `SimulatedPRAM(model, writes)` | an ideal machine, with as many processors as you need: it **checks every memory access** against EREW, CREW or CRCW, and counts steps and work |
56
+ | `ThreadedPRAM(nb_threads)` | runs each step on a few threads (Brent's theorem); use free-threaded Python for a real speed-up |
57
+ | `GpuPRAM(device)` | runs each step as a GPU kernel, with [unigpu](https://pypi.org/project/unigpu/) |
58
+
59
+ **[Documentation](https://laveneau.github.io/unipram/)** (in French, like the
60
+ error messages and the docstrings).
61
+
62
+ ## Install
63
+
64
+ ```bash
65
+ python -m pip install unipram # simulator and threads (needs only NumPy)
66
+ python -m pip install "unipram[metal]" # with a GPU: metal, cuda, cuda13 or opencl
67
+ ```
68
+
69
+ ## Example
70
+
71
+ ```python
72
+ from unipram import Model, SimulatedPRAM
73
+
74
+
75
+ def max_step(pe, jump, t): # one processor, during one step
76
+ if pe + jump < t.size:
77
+ t[pe] = max(t[pe], t[pe + jump])
78
+
79
+
80
+ def maximum(machine, values): # the program
81
+ t = machine.array(values, name="T")
82
+ jump = 1
83
+ while jump < t.size:
84
+ machine.parallel_for(t.size, max_step, jump, t)
85
+ jump *= 2
86
+ return int(machine.read(t)[0])
87
+
88
+
89
+ machine = SimulatedPRAM(Model.CREW)
90
+ print(maximum(machine, [3, 9, 4, 1]), machine.costs())
91
+ # 9 2 pas, travail 8, 4 PE au plus
92
+ ```
93
+
94
+ During a step, every read sees the memory as it was at the start of the step,
95
+ and writes take effect at its end. This algorithm is not EREW, and the
96
+ simulator says so:
97
+
98
+ ```python
99
+ maximum(SimulatedPRAM(Model.EREW), [3, 9, 4, 1])
100
+ # AccessViolation: EREW violé au pas 1 : la case T[1] est lue par 2 PE (0, 1)
101
+ ```
102
+
103
+ Only the simulator checks the accesses: debug there first. An instruction must
104
+ be a plain function, defined with `def` in a file or a notebook. It takes the
105
+ number of its processor, then numbers and shared arrays, and writes only to
106
+ these arrays and its local variables. Every machine refuses anything else.
107
+
108
+ ## See every step
109
+
110
+ ```python
111
+ from unipram import TraceRecorder, TraceView, wait_for_enter
112
+
113
+ trace = TraceRecorder()
114
+ maximum(SimulatedPRAM(Model.CREW, observers=[trace]), [3, 9, 4, 1])
115
+ TraceView(print, pause=wait_for_enter).show(trace.records)
116
+ ```
117
+
118
+ This shows what each processor reads and writes, then the arrays before and
119
+ after the step. Changed cells are in brackets, and large data are shortened.
120
+
121
+ ## Extend it without changing it
122
+
123
+ - **Another model:** `Model("ERCW", concurrent_reads=False, concurrent_writes=True)`.
124
+ - **Another rule for concurrent writes:** a subclass of `WritePolicy`, like
125
+ `ArbitraryWrite`, `ConsistentWrite` and `MergeWrite(operator)`.
126
+ - **Another measure:** a subclass of `StepObserver`, given to the simulator.
127
+ - **Another machine:** a subclass of `PRAM`.
128
+
129
+ To raise an error when the written values are incompatible, a `WritePolicy`
130
+ raises `WriteConflict`.
131
+
132
+ ## Develop
133
+
134
+ ```bash
135
+ python -m pip install -e ".[test]"
136
+ python -m ruff check .
137
+ python -m mypy
138
+ python -m pytest --cov
139
+
140
+ python -m pip install -e ".[docs]"
141
+ python -m mkdocs serve
142
+ ```
143
+
144
+ ## License
145
+
146
+ MIT
@@ -0,0 +1,99 @@
1
+ # unipram: write a PRAM algorithm once, check it, run it anywhere
2
+
3
+ `unipram` is made to **teach parallel algorithms**. A PRAM algorithm is written
4
+ once, in plain Python. The same code then runs on three machines:
5
+
6
+ | Machine | What it does |
7
+ |---|---|
8
+ | `SimulatedPRAM(model, writes)` | an ideal machine, with as many processors as you need: it **checks every memory access** against EREW, CREW or CRCW, and counts steps and work |
9
+ | `ThreadedPRAM(nb_threads)` | runs each step on a few threads (Brent's theorem); use free-threaded Python for a real speed-up |
10
+ | `GpuPRAM(device)` | runs each step as a GPU kernel, with [unigpu](https://pypi.org/project/unigpu/) |
11
+
12
+ **[Documentation](https://laveneau.github.io/unipram/)** (in French, like the
13
+ error messages and the docstrings).
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ python -m pip install unipram # simulator and threads (needs only NumPy)
19
+ python -m pip install "unipram[metal]" # with a GPU: metal, cuda, cuda13 or opencl
20
+ ```
21
+
22
+ ## Example
23
+
24
+ ```python
25
+ from unipram import Model, SimulatedPRAM
26
+
27
+
28
+ def max_step(pe, jump, t): # one processor, during one step
29
+ if pe + jump < t.size:
30
+ t[pe] = max(t[pe], t[pe + jump])
31
+
32
+
33
+ def maximum(machine, values): # the program
34
+ t = machine.array(values, name="T")
35
+ jump = 1
36
+ while jump < t.size:
37
+ machine.parallel_for(t.size, max_step, jump, t)
38
+ jump *= 2
39
+ return int(machine.read(t)[0])
40
+
41
+
42
+ machine = SimulatedPRAM(Model.CREW)
43
+ print(maximum(machine, [3, 9, 4, 1]), machine.costs())
44
+ # 9 2 pas, travail 8, 4 PE au plus
45
+ ```
46
+
47
+ During a step, every read sees the memory as it was at the start of the step,
48
+ and writes take effect at its end. This algorithm is not EREW, and the
49
+ simulator says so:
50
+
51
+ ```python
52
+ maximum(SimulatedPRAM(Model.EREW), [3, 9, 4, 1])
53
+ # AccessViolation: EREW violé au pas 1 : la case T[1] est lue par 2 PE (0, 1)
54
+ ```
55
+
56
+ Only the simulator checks the accesses: debug there first. An instruction must
57
+ be a plain function, defined with `def` in a file or a notebook. It takes the
58
+ number of its processor, then numbers and shared arrays, and writes only to
59
+ these arrays and its local variables. Every machine refuses anything else.
60
+
61
+ ## See every step
62
+
63
+ ```python
64
+ from unipram import TraceRecorder, TraceView, wait_for_enter
65
+
66
+ trace = TraceRecorder()
67
+ maximum(SimulatedPRAM(Model.CREW, observers=[trace]), [3, 9, 4, 1])
68
+ TraceView(print, pause=wait_for_enter).show(trace.records)
69
+ ```
70
+
71
+ This shows what each processor reads and writes, then the arrays before and
72
+ after the step. Changed cells are in brackets, and large data are shortened.
73
+
74
+ ## Extend it without changing it
75
+
76
+ - **Another model:** `Model("ERCW", concurrent_reads=False, concurrent_writes=True)`.
77
+ - **Another rule for concurrent writes:** a subclass of `WritePolicy`, like
78
+ `ArbitraryWrite`, `ConsistentWrite` and `MergeWrite(operator)`.
79
+ - **Another measure:** a subclass of `StepObserver`, given to the simulator.
80
+ - **Another machine:** a subclass of `PRAM`.
81
+
82
+ To raise an error when the written values are incompatible, a `WritePolicy`
83
+ raises `WriteConflict`.
84
+
85
+ ## Develop
86
+
87
+ ```bash
88
+ python -m pip install -e ".[test]"
89
+ python -m ruff check .
90
+ python -m mypy
91
+ python -m pytest --cov
92
+
93
+ python -m pip install -e ".[docs]"
94
+ python -m mkdocs serve
95
+ ```
96
+
97
+ ## License
98
+
99
+ MIT
@@ -0,0 +1,5 @@
1
+ /* Dans un tableau, un nom de classe ne se coupe pas en deux. */
2
+ .md-typeset td:first-child code {
3
+ white-space: nowrap;
4
+ word-break: normal;
5
+ }
@@ -0,0 +1,95 @@
1
+ # Étendre unipram
2
+
3
+ On ajoute un modèle, une stratégie ou un observateur **sans modifier** `unipram`.
4
+
5
+ ## Un modèle
6
+
7
+ Un modèle est une simple valeur :
8
+
9
+ ```python
10
+ from unipram import Model, SimulatedPRAM
11
+
12
+ ERCW = Model("ERCW", concurrent_reads=False, concurrent_writes=True)
13
+ machine = SimulatedPRAM(ERCW)
14
+ ```
15
+
16
+ ## Une stratégie d'écriture
17
+
18
+ Une stratégie est une sous-classe de `WritePolicy`. Sa méthode `resolve` reçoit les
19
+ valeurs écrites dans une case, dans l'ordre des PE. Il y en a au moins une. Si
20
+ elles sont incompatibles, elle lève une `WriteConflict`, que le simulateur
21
+ transforme en `AccessViolation`.
22
+
23
+ ```python
24
+ from unipram import AccessViolation, WriteConflict, WritePolicy
25
+
26
+
27
+ class AtMostTwo(WritePolicy):
28
+ """La dernière valeur, si deux PE au plus écrivent la case."""
29
+
30
+ def resolve(self, values):
31
+ if len(values) > 2:
32
+ raise WriteConflict(f"{len(values)} valeurs pour une case")
33
+ return values[-1]
34
+
35
+
36
+ def write_step(pe, t):
37
+ t[0] = pe
38
+
39
+
40
+ machine = SimulatedPRAM(Model.CRCW, writes=AtMostTwo())
41
+ t = machine.zeros(1, name="T")
42
+ machine.parallel_for(2, write_step, t)
43
+ print(machine.read(t)[0])
44
+ try:
45
+ machine.parallel_for(3, write_step, t)
46
+ except AccessViolation as violation:
47
+ print(violation)
48
+ ```
49
+
50
+ ```text
51
+ 1
52
+ pas 2, case T[0] : 3 valeurs pour une case
53
+ ```
54
+
55
+ ## Un observateur
56
+
57
+ Un observateur est une sous-classe de `StepObserver`. Il redéfinit seulement les
58
+ méthodes dont il a besoin. Celui-ci compte les lectures :
59
+
60
+ ```python
61
+ from unipram import StepObserver
62
+
63
+
64
+ class ReadCounter(StepObserver):
65
+ def __init__(self):
66
+ self.reads = 0
67
+
68
+ def step_finished(self, log):
69
+ self.reads += len(log.reads)
70
+
71
+
72
+ def copy_step(pe, source, target):
73
+ target[pe] = source[pe]
74
+
75
+
76
+ counter = ReadCounter()
77
+ machine = SimulatedPRAM(observers=[counter])
78
+ machine.parallel_for(3, copy_step, machine.array([1, 2, 3]), machine.zeros(3))
79
+ print(counter.reads)
80
+ ```
81
+
82
+ ```text
83
+ 3
84
+ ```
85
+
86
+ ## Une machine
87
+
88
+ Une machine est une sous-classe de `PRAM`. Elle écrit trois méthodes : `_allocate`,
89
+ `_read` et `_execute`. La classe `PRAM` vérifie les instructions et leurs
90
+ arguments, puis compte les coûts. Elle n'appelle `_execute` que s'il y a au moins
91
+ un PE.
92
+
93
+ Une nouvelle machine doit pouvoir remplacer les autres. Pour le vérifier,
94
+ ajoutez-la à `MACHINES` dans `tests/conftest.py` : tous les tests communs seront
95
+ aussi lancés sur elle.
@@ -0,0 +1,67 @@
1
+ # unipram
2
+
3
+ `unipram` sert à **apprendre l'algorithmique parallèle** sur le modèle PRAM
4
+ (*Parallel Random Access Machine*). Vous écrivez un algorithme une seule fois, en
5
+ Python, puis vous l'exécutez sur trois machines :
6
+
7
+ | Machine | Rôle |
8
+ |---|---|
9
+ | `SimulatedPRAM` | Une machine idéale, avec autant de processeurs (PE) qu'il faut. Elle **vérifie chaque accès** à la mémoire partagée (EREW, CREW ou CRCW), et compte les pas et le travail. |
10
+ | `ThreadedPRAM` | Quelques threads se partagent les PE (théorème de Brent). |
11
+ | `GpuPRAM` | Chaque PE est un thread du GPU, avec [unigpu](https://pypi.org/project/unigpu/). |
12
+
13
+ La première suffit pour écrire et tester un algorithme. Les deux autres servent à
14
+ mesurer ce que coûte un pas PRAM sur une vraie machine.
15
+
16
+ ## Installation
17
+
18
+ Il faut Python 3.12 ou plus récent.
19
+
20
+ ```bash
21
+ python -m pip install unipram
22
+ ```
23
+
24
+ Cette commande installe seulement `unipram` et NumPy. Elle suffit pour le
25
+ simulateur et les threads. Pour un GPU, voir [Threads et GPU](machines.md#gpu).
26
+
27
+ ## Premier exemple
28
+
29
+ Cet algorithme cherche le maximum d'un tableau. Enregistrez-le dans un fichier,
30
+ puis lancez-le.
31
+
32
+ ```python
33
+ from unipram import Model, SimulatedPRAM
34
+
35
+
36
+ def max_step(pe, jump, t): # ce que fait un PE pendant un pas
37
+ if pe + jump < t.size:
38
+ t[pe] = max(t[pe], t[pe + jump])
39
+
40
+
41
+ def maximum(machine, values): # le programme, qui enchaîne les pas
42
+ t = machine.array(values, name="T")
43
+ jump = 1
44
+ while jump < t.size:
45
+ machine.parallel_for(t.size, max_step, jump, t)
46
+ jump *= 2
47
+ return int(machine.read(t)[0])
48
+
49
+
50
+ machine = SimulatedPRAM(Model.CREW)
51
+ print(maximum(machine, [3, 9, 4, 1]))
52
+ print(machine.costs())
53
+ ```
54
+
55
+ ```text
56
+ 9
57
+ 2 pas, travail 8, 4 PE au plus
58
+ ```
59
+
60
+ Le programme ne dépend pas de la machine : `maximum` fonctionne aussi avec
61
+ `ThreadedPRAM` et `GpuPRAM`.
62
+
63
+ ## Et ensuite ?
64
+
65
+ 1. [Écrire un programme](programme.md) : les règles d'une instruction.
66
+ 2. [Vérifier et corriger](verifier.md) : les modèles, et les messages d'erreur.
67
+ 3. [Mesurer et observer](observer.md) : les coûts, et l'exécution pas à pas.
@@ -0,0 +1,107 @@
1
+ # Threads et GPU
2
+
3
+ Ces machines exécutent le même programme que le simulateur. Elles refusent les
4
+ mêmes instructions et comptent les mêmes coûts, mais **elles ne vérifient ni le
5
+ modèle ni les indices**. Passez toujours par le simulateur d'abord.
6
+
7
+ Si un pas échoue sur l'une d'elles, des écritures ont pu avoir lieu.
8
+
9
+ ## Threads
10
+
11
+ Utilisez `with` : la machine arrête ses threads à la fin du bloc.
12
+
13
+ ```python
14
+ from unipram import ThreadedPRAM
15
+
16
+
17
+ def square_step(pe, t):
18
+ t[pe] = t[pe] * t[pe]
19
+
20
+
21
+ def squares(machine, values):
22
+ t = machine.array(values)
23
+ machine.parallel_for(t.size, square_step, t)
24
+ return machine.read(t)
25
+
26
+
27
+ with ThreadedPRAM(nb_threads=4) as machine:
28
+ print(squares(machine, [1, 2, 3, 4]))
29
+ ```
30
+
31
+ ```text
32
+ [ 1 4 9 16]
33
+ ```
34
+
35
+ Sans `nb_threads`, la machine utilise autant de threads qu'il y a de cœurs. À
36
+ chaque pas, les PE sont répartis entre les threads, et la fin du pas est une
37
+ barrière.
38
+
39
+ Avec un Python ordinaire, le verrou global (GIL) empêche les threads de calculer
40
+ en même temps : le résultat est juste, mais il n'arrive pas plus vite. La machine
41
+ affiche alors un avertissement. Pour un vrai gain, utilisez un Python sans GIL,
42
+ comme Python 3.14t.
43
+
44
+ ## GPU
45
+
46
+ `GpuPRAM` utilise un autre paquet, [unigpu](https://pypi.org/project/unigpu/).
47
+ Choisissez l'option qui correspond à votre GPU :
48
+
49
+ ```bash
50
+ python -m pip install "unipram[metal]" # Mac
51
+ python -m pip install "unipram[cuda]" # NVIDIA, avec CUDA 12
52
+ python -m pip install "unipram[cuda13]" # NVIDIA, avec CUDA 13
53
+ python -m pip install "unipram[opencl]" # AMD, Intel..., avec un pilote OpenCL
54
+ python -m pip install "unipram[gpu]" # sans GPU : le simulateur d'unigpu
55
+ ```
56
+
57
+ ```python
58
+ from unipram import GpuPRAM
59
+
60
+ print(squares(GpuPRAM("sim"), [1, 2, 3, 4]))
61
+ ```
62
+
63
+ ```text
64
+ [ 1 4 9 16]
65
+ ```
66
+
67
+ Remplacez `"sim"` par `"metal"`, `"cuda"` ou `"opencl"`. Sans argument, la machine
68
+ utilise le périphérique courant d'unigpu. Chaque pas est un noyau, avec un thread
69
+ par PE.
70
+
71
+ !!! warning "Deux simulateurs différents"
72
+ `SimulatedPRAM` **vérifie un algorithme PRAM** et n'utilise pas unigpu.
73
+ `GpuPRAM("sim")` exécute des noyaux avec le simulateur d'unigpu, sans GPU : il
74
+ ne vérifie pas le modèle PRAM.
75
+
76
+ ## Pourquoi le résultat est-il le même ?
77
+
78
+ Les threads et le GPU ne sont pas synchrones. Avant chaque pas, la machine copie
79
+ donc chaque tableau que l'instruction écrit. Elle réécrit aussi l'instruction,
80
+ pour qu'elle lise la copie et écrive dans le tableau :
81
+
82
+ ```text
83
+ t[pe] = max(t[pe], t[pe + jump]) # votre instruction
84
+ t[pe] = max(old_t[pe], old_t[pe + jump]) # ce qui est exécuté
85
+ ```
86
+
87
+ Chaque pas coûte donc une copie complète de ces tableaux, même s'il n'utilise que
88
+ quelques PE.
89
+
90
+ ## Choisir une machine par son nom
91
+
92
+ `machine_factories()` associe un nom à chaque machine. C'est utile pour une option
93
+ de la ligne de commande :
94
+
95
+ ```python
96
+ from unipram import machine_factories
97
+
98
+ factories = machine_factories(device="sim", nb_threads=2)
99
+ print(list(factories))
100
+ with factories["simulateur"]() as machine:
101
+ print(squares(machine, [1, 2, 3, 4]))
102
+ ```
103
+
104
+ ```text
105
+ ['simulateur', 'threads', 'gpu']
106
+ [ 1 4 9 16]
107
+ ```
@@ -0,0 +1,98 @@
1
+ # Mesurer et observer
2
+
3
+ ## Les coûts
4
+
5
+ Toutes les machines comptent :
6
+
7
+ - `machine.steps` : le nombre de pas, c'est-à-dire le temps parallèle ;
8
+ - `machine.work` : le travail, c'est-à-dire la somme des nombres de PE de chaque
9
+ pas ;
10
+ - `machine.processors` : le plus grand nombre de PE dans un pas.
11
+
12
+ `machine.costs()` les résume. Un pas compte pour 1, même si l'instruction contient
13
+ une boucle. C'est donc à vous de vérifier que chaque PE fait un nombre constant
14
+ d'opérations. Le simulateur vous y aide, avec `accesses_per_step` ci-dessous.
15
+
16
+ ## Les accès à la mémoire
17
+
18
+ Les mesures du simulateur sont dans `machine.statistics` :
19
+
20
+ ```python
21
+ from unipram import Model, SimulatedPRAM
22
+
23
+
24
+ def max_step(pe, jump, t):
25
+ if pe + jump < t.size:
26
+ t[pe] = max(t[pe], t[pe + jump])
27
+
28
+
29
+ def maximum(machine, values):
30
+ t = machine.array(values, name="T")
31
+ jump = 1
32
+ while jump < t.size:
33
+ machine.parallel_for(t.size, max_step, jump, t)
34
+ jump *= 2
35
+ return int(machine.read(t)[0])
36
+
37
+
38
+ machine = SimulatedPRAM(Model.CRCW)
39
+ maximum(machine, [3, 9, 4, 1])
40
+ print("lecteurs d'une case :", machine.statistics.concurrent_reads)
41
+ print("écrivains d'une case :", machine.statistics.concurrent_writes)
42
+ print("accès d'un PE :", machine.statistics.accesses_per_step)
43
+ print("modèle suffisant :", machine.statistics.weakest_model().name)
44
+ ```
45
+
46
+ ```text
47
+ lecteurs d'une case : 2
48
+ écrivains d'une case : 1
49
+ accès d'un PE : 3
50
+ modèle suffisant : CREW
51
+ ```
52
+
53
+ Ces nombres sont les plus grands atteints dans un même pas. `weakest_model()`
54
+ indique le modèle le plus faible qui suffit **pour cette exécution**, pas pour
55
+ toutes les données.
56
+
57
+ ## L'exécution pas à pas
58
+
59
+ Un `TraceRecorder` garde la mémoire avant et après chaque pas, et un `TraceView`
60
+ l'affiche. Les cases modifiées sont entre crochets.
61
+
62
+ ```python
63
+ from unipram import TraceRecorder, TraceView
64
+
65
+ trace = TraceRecorder()
66
+ maximum(SimulatedPRAM(Model.CREW, observers=[trace]), [3, 9, 4, 1])
67
+ TraceView(lambda line: print(line.expandtabs(2))).show(trace.records)
68
+ ```
69
+
70
+ ```text
71
+ pas 1 : max_step, 4 PE
72
+ PE 0 : lit T[0] = 3, T[1] = 9 ; écrit T[0] = 9
73
+ PE 1 : lit T[1] = 9, T[2] = 4 ; écrit T[1] = 9
74
+ PE 2 : lit T[2] = 4, T[3] = 1 ; écrit T[2] = 4
75
+ PE 3 : aucun accès à la mémoire
76
+ case | 0 1 2 3
77
+ T avant | 3 9 4 1
78
+ T après | [9] 9 4 1
79
+ pas 2 : max_step, 4 PE
80
+ PE 0 : lit T[0] = 9, T[2] = 4 ; écrit T[0] = 9
81
+ PE 1 : lit T[1] = 9, T[3] = 1 ; écrit T[1] = 9
82
+ PE 2 : aucun accès à la mémoire
83
+ PE 3 : aucun accès à la mémoire
84
+ case | 0 1 2 3
85
+ T avant | 9 9 4 1
86
+ T après | 9 9 4 1
87
+ ```
88
+
89
+ Pour faire une pause après chaque pas, utilisez
90
+ `TraceView(print, pause=wait_for_enter)`. Les pauses ont lieu pendant l'affichage :
91
+ l'exécution est déjà terminée. Les grands tableaux et les longues listes de PE
92
+ sont abrégés. Les options `max_cells` et `max_pe` changent ces limites.
93
+
94
+ Si un pas échoue, il est aussi enregistré. Pour l'afficher, entourez le programme
95
+ d'un `try`, et appelez `show` dans le `finally`.
96
+
97
+ !!! note
98
+ La trace copie tous les tableaux à chaque pas : utilisez de petites données.