okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Yasei-no-otokobench: report Coder IQ1_M on Threadripper 3990X and RX 6900 XT (#628)cc86ad90d

main
10.1 KiB219 linesraw
1"""Read-only Windows processor group / NUMA / affinity probe.
2Runs only in this helper process; affinity is changed only on its own temporary test threads.
3"""
4import ctypes as C
5import json
6import os
7import platform
8import sys
9import struct
10import threading
11import time
12from pathlib import Path
13
14OUT = Path(__file__).resolve().parent
15k32 = C.WinDLL("kernel32", use_last_error=True)
16DWORD = C.c_uint32
17WORD = C.c_uint16
18BYTE = C.c_ubyte
19KAFFINITY = C.c_size_t
20ALL_PROCESSOR_GROUPS = 0xFFFF
21
22class GROUP_AFFINITY(C.Structure):
23    _fields_ = [("Mask", KAFFINITY), ("Group", WORD), ("Reserved", WORD * 3)]
24
25class PROCESSOR_NUMBER(C.Structure):
26    _fields_ = [("Group", WORD), ("Number", BYTE), ("Reserved", BYTE)]
27
28# Declare only APIs used by the probe; all processor IDs are group-relative.
29k32.GetActiveProcessorGroupCount.restype = WORD
30k32.GetActiveProcessorCount.argtypes = [WORD]
31k32.GetActiveProcessorCount.restype = DWORD
32k32.GetCurrentThread.restype = C.c_void_p
33k32.GetCurrentProcessorNumberEx.argtypes = [C.POINTER(PROCESSOR_NUMBER)]
34k32.SetThreadAffinityMask.argtypes = [C.c_void_p, KAFFINITY]
35k32.SetThreadAffinityMask.restype = KAFFINITY
36k32.GetThreadGroupAffinity.argtypes = [C.c_void_p, C.POINTER(GROUP_AFFINITY)]
37k32.GetThreadGroupAffinity.restype = C.c_int
38k32.SetThreadGroupAffinity.argtypes = [C.c_void_p, C.POINTER(GROUP_AFFINITY), C.POINTER(GROUP_AFFINITY)]
39k32.SetThreadGroupAffinity.restype = C.c_int
40k32.GetLogicalProcessorInformationEx.argtypes = [DWORD, C.c_void_p, C.POINTER(DWORD)]
41k32.GetLogicalProcessorInformationEx.restype = C.c_int
42
43
44def api_error(name):
45    raise OSError(C.get_last_error(), f"{name} failed")
46
47
48def masks(records_relation):
49    needed = DWORD(0)
50    C.set_last_error(0)
51    ok = k32.GetLogicalProcessorInformationEx(records_relation, None, C.byref(needed))
52    if ok or needed.value == 0:
53        api_error("GetLogicalProcessorInformationEx(size query)")
54    buf = C.create_string_buffer(needed.value)
55    if not k32.GetLogicalProcessorInformationEx(records_relation, C.cast(buf, C.c_void_p), C.byref(needed)):
56        api_error("GetLogicalProcessorInformationEx(data query)")
57    records = []
58    pos = 0
59    while pos < needed.value:
60        relationship, size = struct.unpack_from("=II", buf.raw, pos)
61        if size < 8 or pos + size > needed.value:
62            raise RuntimeError(f"invalid relation record at offset {pos}: size={size}, length={needed.value}")
63        # RelationNumaNodeEx is requested with 6 but, on this Windows build,
64        # the returned record's Relationship field is RelationNumaNode (1).
65        if relationship == records_relation or (records_relation == 6 and relationship == 1):
66            records.append((pos, size))
67        pos += size
68    if pos != needed.value:
69        raise RuntimeError(f"record sequence ended at {pos}, expected {needed.value}")
70    return buf, records
71
72
73def parse_affinities(buf, offset, count):
74    out = []
75    for i in range(count):
76        mask, group = struct.unpack_from("=QH", buf.raw, offset + i * C.sizeof(GROUP_AFFINITY))
77        processors = [bit for bit in range(64) if mask & (1 << bit)]
78        out.append({"group": group, "mask_hex": f"0x{mask:016X}", "processors": processors})
79    return out
80
81
82def parse_cores():
83    buf, records = masks(0)  # RelationProcessorCore
84    cores = []
85    for ordinal, (pos, size) in enumerate(records):
86        # SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX union starts at byte 8;
87        # PROCESSOR_RELATIONSHIP.GroupCount is byte 22 in that union, first GROUP_AFFINITY byte 24.
88        count = struct.unpack_from("=H", buf.raw, pos + 30)[0]
89        groups = parse_affinities(buf, pos + 32, count)
90        cores.append({"core_record": ordinal, "groups": groups})
91    return cores
92
93
94def parse_numa():
95    buf, records = masks(6)  # RelationNumaNodeEx; full masks span processor groups
96    nodes = []
97    for pos, size in records:
98        node = struct.unpack_from("=I", buf.raw, pos + 8)[0]
99        count = struct.unpack_from("=H", buf.raw, pos + 30)[0]
100        groups = parse_affinities(buf, pos + 32, count)
101        nodes.append({"node": node, "groups": groups, "record_size": size})
102    return nodes
103
104
105def affinity_snapshot(handle):
106    ga = GROUP_AFFINITY()
107    if not k32.GetThreadGroupAffinity(handle, C.byref(ga)):
108        api_error("GetThreadGroupAffinity")
109    pn = PROCESSOR_NUMBER()
110    k32.GetCurrentProcessorNumberEx(C.byref(pn))
111    return {"group": int(ga.Group), "mask_hex": f"0x{ga.Mask:016X}",
112            "mask_processors": [i for i in range(64) if ga.Mask & (1 << i)],
113            "current_processor": {"group": int(pn.Group), "number": int(pn.Number)}}
114
115
116def legacy_test(target_group, target_processor, move_group_first):
117    done = threading.Event()
118    result = {}
119    def body():
120        handle = k32.GetCurrentThread()
121        original = GROUP_AFFINITY()
122        moved = False
123        previous_mask = 0
124        try:
125            if move_group_first:
126                ga = GROUP_AFFINITY()
127                ga.Mask = KAFFINITY(1 << target_processor).value
128                ga.Group = target_group
129                if not k32.SetThreadGroupAffinity(handle, C.byref(ga), C.byref(original)):
130                    api_error("SetThreadGroupAffinity(test setup)")
131                moved = True
132            result["before"] = affinity_snapshot(handle)
133            requested = KAFFINITY(1 << target_processor).value
134            C.set_last_error(0)
135            previous_mask = k32.SetThreadAffinityMask(handle, requested)
136            result["set_thread_affinity_mask"] = {"requested_hex": f"0x{requested:016X}",
137                "succeeded": bool(previous_mask), "returned_previous_hex": f"0x{previous_mask:016X}",
138                "error": None if previous_mask else C.get_last_error()}
139            if previous_mask:
140                # Give the scheduler time to honor the single-processor mask before sampling current CPU.
141                end = time.perf_counter() + 0.02
142                while time.perf_counter() < end:
143                    pass
144            result["after"] = affinity_snapshot(handle)
145        except Exception as exc:
146            result["error"] = f"{type(exc).__name__}: {exc}"
147        finally:
148            # Restore only this probe thread's temporary affinity before it exits.
149            if previous_mask:
150                k32.SetThreadAffinityMask(handle, previous_mask)
151            if moved:
152                k32.SetThreadGroupAffinity(handle, C.byref(original), None)
153            done.set()
154    t = threading.Thread(target=body, name=f"affinity-probe-g{target_group}-p{target_processor}")
155    t.start()
156    done.wait(5)
157    t.join(5)
158    if t.is_alive():
159        raise RuntimeError("affinity test thread did not finish")
160    result["expected_processor"] = {"group": target_group, "number": target_processor}
161    return result
162
163
164def main():
165    group_count = int(k32.GetActiveProcessorGroupCount())
166    group_counts = [int(k32.GetActiveProcessorCount(i)) for i in range(group_count)]
167    cores = parse_cores()
168    numa = parse_numa()
169    by_group = {g: [] for g in range(group_count)}
170    for core in cores:
171        for entry in core["groups"]:
172            by_group.setdefault(entry["group"], []).append(entry["processors"])
173    summaries = {}
174    for group, core_lists in by_group.items():
175        summaries[str(group)] = {
176            "physical_core_records": len(core_lists),
177            "logical_processors_in_core_records": sum(len(x) for x in core_lists),
178            "representative_physical_core_logical_ids": [x[0] for x in core_lists],
179            "first_4_core_smt_masks": core_lists[:4],
180            "last_2_core_smt_masks": core_lists[-2:],
181        }
182    tests = []
183    # The first test requests a group-0 flat CPU ID on a newly created thread,
184    # which inherits this process's primary group. The second sets group 1
185    # explicitly, showing that the legacy mask is group-relative once the group
186    # is selected. The default engine path has no SetThreadGroupAffinity call.
187    reps = {g: (core_lists[0][0] if core_lists and core_lists[0] else 0)
188            for g, core_lists in by_group.items()}
189    if 0 in reps:
190        tests.append({"case": "legacy_mask_for_flattened_group0_core_on_inherited_primary_group",
191                      "target_group": 0, "target_processor": reps[0],
192                      "move_group_first": False, "result": legacy_test(0, reps[0], False)})
193    if 1 in reps:
194        tests.append({"case": "group1_explicit_group_affinity_then_legacy_mask", "target_group": 1,
195                      "target_processor": reps[1], "move_group_first": True,
196                      "result": legacy_test(1, reps[1], True)})
197    result = {
198        "probe": "windows_processor_groups_affinity_probe.py",
199        "safety": "Separate helper process. Affinity modified only on its own short-lived Python test threads; no Strata/model/server/process affinity was queried or changed.",
200        "timestamp_local": time.strftime("%Y-%m-%d %H:%M:%S %Z"),
201        "os": {"platform": platform.platform(), "version": platform.version(), "python": sys.version,
202              "pointer_bits": C.sizeof(C.c_void_p) * 8, "processor_count": os.cpu_count()},
203        "helper_main_thread_affinity": affinity_snapshot(k32.GetCurrentThread()),
204        "groups": {"active_group_count": group_count, "active_processors_per_group": group_counts,
205                   "total_active_processors_api": int(k32.GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)),
206                   "physical_core_records": len(cores), "cores_by_group": summaries},
207        "numa_nodes_relation_numa_node_ex": numa,
208        "legacy_set_thread_affinity_tests": tests,
209        "source_notes": {
210            "core_mask_parsing": "SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX RelationProcessorCore; all GROUP_AFFINITY records read.",
211            "numa_mask_parsing": "RelationNumaNodeEx (relationship 6); variable GroupCount and full per-group masks read.",
212            "affinity_scope": "SetThreadGroupAffinity and SetThreadAffinityMask applied only to test threads created by this script. GetThreadGroupAffinity and GetCurrentProcessorNumberEx read back their placement.",
213        },
214    }
215    (OUT / "probe-results.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
216    print(json.dumps(result, indent=2))
217
218if __name__ == "__main__":
219    main()