s42chen commited on
Commit
afaec48
·
verified ·
1 Parent(s): 587425d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. plots/scalar-task-progression.svg +0 -0
  2. reviews/fairness-20261031/per-task/atomistic-materials.json +168 -0
  3. reviews/fairness-20261031/per-task/crystal-structure-generation.json +121 -0
  4. reviews/fairness-20261031/per-task/fruit-fly-neuron-reconstruction.json +227 -0
  5. reviews/fairness-20261031/per-task/molecular-pretraining-transfer.json +209 -0
  6. reviews/fairness-20261031/per-task/probabilistic-global-weather.json +194 -0
  7. shared/package-files/d6/d60192201c9d72dc0ecb4b9d51754632551ca3d1060a60f9a710950111511895/h19-us +0 -0
  8. shared/package-files/d6/d60192201c9d72dc0ecb4b9d51754632551ca3d1060a60f9a710950111511895/h19us +0 -0
  9. shared/package-files/d6/d60204d1c6facf9b83b6964a8df47e10b723d271615721353a942ac835a8d33a/wy520-24 +0 -0
  10. shared/package-files/d6/d60204d1c6facf9b83b6964a8df47e10b723d271615721353a942ac835a8d33a/wyse520-24 +0 -0
  11. shared/package-files/d6/d6073d10c880d7f39c13f6c77d6418f6bc372adae5027eae6139c1680f28a6c9/basic4 +0 -0
  12. shared/package-files/d6/d6073d10c880d7f39c13f6c77d6418f6bc372adae5027eae6139c1680f28a6c9/mai +0 -0
  13. shared/package-files/d6/d60e39a1cd75e59651dc27cc5b56c23ec785e404f3e177fa221dba351ab28dfb/decomp_cholesky.py +21 -0
  14. shared/package-files/d6/d611a87944137b0e68d039c28cb579fa139f12e4a8206397181caae4aa403fb0/test_deprecate.py +63 -0
  15. shared/package-files/d6/d617f6bdf5c9ff46889dc63e6d9320c794d74f3188e3d6027d5c42858aec2e7a/test_bisect_k_means.py +158 -0
  16. shared/package-files/d6/d61a25ad2b1d631a7512ca1adb27d11cb8e26250918b78d8672db25a6eb66155/alias.py +78 -0
  17. shared/package-files/d6/d61cbc9dfcc6668ecbad20a8bfd94b72662f2caf744c8f6e85e11c1749207480/CUDAGeneratorImpl.h +138 -0
  18. shared/package-files/d6/d61cbd1738894ba8f836c0545ff843b578996848c9aca201b2ba8882dea2be43/_semi_structured_conversions.py +275 -0
  19. shared/package-files/d6/d61cf1c1a30d2506cc308ae812295e691a24a866cb3fc860177e4152bedda3d2/binary_cross_entropy_backward_native.h +24 -0
  20. shared/package-files/d6/d6299b00fb957aeff2f9dd718a5f4c25471e6e51704738855a1391ad7e676796/results_exact_initial_local_linear_trend_R.csv +12 -0
  21. shared/package-files/d6/d62e704a0000340ef3d7def67fd9b42f2b5e112734e3293de037e703cea2ad70/att5420-nl +0 -0
  22. shared/package-files/d6/d6318382b231dfe4d638234c482e33c6665aecb1f2314ebd0d7877875d818da8/test_spectral_bipartivity.py +80 -0
  23. shared/package-files/d6/d63221cd4ede06f637a5b5b72d9a09842394d8a5aa82dcb91e043a541608a795/utils.py +187 -0
  24. shared/package-files/d6/d635f1005b25da2bd7953f52b0638ceecd6ebd2d94284b96ccd600fdb4ed4ba5/contains.py +48 -0
  25. shared/package-files/d6/d6373e1408ef90a9e60a3873f3ec908042ab37fb159b3022f03568cbdfcaf004/Casey +0 -0
  26. shared/package-files/d6/d63e4b7887f677be27d65cef98e4133d3bab49f264d85230576a1cf00f071416/group_norm_expanded_weights.py +64 -0
  27. shared/package-files/d6/d63eb28e9e3f5a5c5c0d748128e93e21fac46d6b42e07bdb2081de336c76e72b/test_to_timestamp.py +154 -0
  28. shared/package-files/d6/d63fa4403cf0fe8a47451939edb425f1d3f9005ee0f2333f12e76bb2c53979c5/constant_propagation.h +32 -0
  29. shared/package-files/d6/d64431841511ea36f8fcaa8040769fdbdced56a386692807193dbc8301fe2ac8/test_to_csv.py +179 -0
  30. shared/package-files/d6/d6456b0a1ce260e9f3f1ad9bac56981344dac7e82628a078434a75fe9aafc124/_convert_indices_from_coo_to_csr.h +39 -0
  31. shared/package-files/d6/d64be755da43107b26fa96414d885b356200b5c3335a80cf2642e921d789146a/_knn.py +411 -0
  32. shared/package-files/d6/d64eaf3a093a6c3eff4219a0750ce20823d67b80838ea1bcfe005b369ca971a9/narrow_copy_ops.h +39 -0
  33. shared/package-files/d6/d654e7dbb66735047c936f6caaf1089e79d23db7e9f4eeb9642cba995c00017d/att620-103k-w +0 -0
  34. shared/package-files/d6/d658a0be19c1975e06e2be07afd0ff1b8baccfcd44ce0c702039256393f58410/ros.py +612 -0
  35. shared/package-files/d6/d65c2a89d2a4e5cdd32a87a7db71b6f5fd65c8bd74fb4774f7dc35b254593873/cudnn_affine_grid_generator_native.h +22 -0
  36. shared/package-files/d6/d668b1518304dba5f75c2f51d689eb9db1fdd5be52f7828fa6755945cd19d020/cyaml.pyi +63 -0
  37. shared/package-files/d6/d66ab1c4b5c4492ce5888976e2e0a29c01707a0b8bf213d2d3aa4a3d27fab3f2/slow_conv3d_forward_ops.h +39 -0
  38. shared/package-files/d6/d66fbf2ce0769a5dfcaaf71fd504355ddd80af0c263fb4695d1dded0feed0be7/_testing.py +1454 -0
  39. shared/package-files/d6/d67a2b78b4428693a07928f4b894f599e862065f27821df71ae73b29dbf36183/METADATA +66 -0
  40. shared/package-files/d6/d67a78c1e3af987148e25d1b6ce379c71492abe98f24ec85ed0e69409a5e676f/debugger.py +1120 -0
  41. shared/package-files/d6/d67beab91315de97e2a7313f0dbefbc5003662256c864b256eb47a2896573769/application.pyi +16 -0
  42. shared/package-files/d6/d67e1aed4c6de22de98b191f1150a1d1f8b3f04c4679a790fa4754cc5a780e5a/CUDADevice.h +23 -0
  43. shared/package-files/d6/d681474dbfb26dc4ea2d79b4af564e5607583131e51a836cf8f82fbb1e747771/Aqtobe +0 -0
  44. shared/package-files/d6/d6816dd21d1187b267176ab0d50b53d17ce451a9d5f976fd5e2f41f597076880/chapel.py +140 -0
  45. shared/package-files/d6/d6836634278d0962c758bf6fc73ab790bebb366b4e502f08afd98bafcd6951b1/dropout_compositeimplicitautograd_dispatch.h +24 -0
  46. shared/package-files/d6/d689ccaa33ffa701450012a45c024ca4bb2ca767826a361bfc399f7465bcf1d8/contentmanager.pyi +11 -0
  47. shared/package-files/d6/d693b0d186a757968facc1b0aa401393c3935e6ea22c5da2b9460a6d47f56fa4/log_level.py +14 -0
  48. shared/package-files/d6/d694d22b9954e8be40246e47df93d3210b47608a653288a96bb2a477f9bd1cd4/multipart.pyi +4 -0
  49. shared/package-files/d6/d694d6648579e11959bb8046b86028cb1ed9f50abcddc20127eaafe044c498a9/firstlinefinder.py +104 -0
  50. shared/package-files/d6/d696ba65b8f27cc5a1f9a634ef4564c007f587c9432b55db9387df6f3348b72e/transformPen.py +114 -0
plots/scalar-task-progression.svg CHANGED
reviews/fairness-20261031/per-task/atomistic-materials.json ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task": "atomistic-materials",
3
+ "run_root": "/weka/oe-adapt-default/stevenc/science-speedrun-runs/atomistic-materials-astra-xhigh-1h100-48h-20261020b",
4
+ "containers": 6,
5
+ "turns": 10,
6
+ "charged_seconds": 172800,
7
+ "research_state_error": null,
8
+ "timeline_note": "Known context said 1 recovery; the run actually had 6 containers (attempts/001-005 + root preflight) and 10 Codex invocations (10 thread.started in trajectory.jsonl; item ids restart at item_0 in each, so evidence below is cited as T<invocation> item_<id> / trajectory line L<n>). Wall clock from agent/sessions rollout: T1 03:51:56Z Oct 21 -> killed 13:28:41Z (Beaker: node cordoned, Xid 48); T2 13:31:21Z -> operator pause 06:10:46Z Oct 22 (94,586 s charged); T3 06:16:05Z -> capacity turn.failed 08:35:31Z; T4/T5 08:36/08:37Z instant capacity failures; T6 08:40:10Z -> capacity turn.failed 11:06:12Z; T7 11:10:12Z -> container died ~18:24-18:28Z (last activity 18:23:38Z); T8 18:28:27Z -> died ~21:26-21:29Z; T9 21:29:17Z -> died ~00:01Z Oct 23; T10 00:01:48Z -> deadline 04:07:58Z. Not affected by the Oct 23 ENOSPC (that hit sibling runs at 11:19Z Oct 23, 7 h after this run finished; no 'No space left'/ENOSPC in any command output), although shared Weka free space fell from 16.0 TB (attempt 1) to 2.8 TB (attempt 6) during the run.",
9
+ "incidents": [
10
+ {
11
+ "kind": "4 (infrastructure interruption: GPU node hardware failure)",
12
+ "ownership": "infrastructure",
13
+ "when_charged_seconds": 34600,
14
+ "evidence": [
15
+ "operator-pause.json jobs[0]: exited 2026-10-21T13:28:50Z exitCode 143, canceledFor 'node ... is cordoned: Node unhealthy due to unrecoverable Xid error code 48'",
16
+ "attempts/002/preflight-result.json (new container preflight 13:31Z)",
17
+ "T1 item_1932 (L3565, conductivity in CPU transport solve), T1 item_1947 (L3592) last message; T2 item_11 (L3615) 'The environment restarted ... interrupting validation'; T2 item_18 (L3628) 'The conductivity run ended without a prediction, so I'll retain its failure penalty'",
18
+ "rollout: last T1 record 13:28:34Z, T2 prompt 13:31:21Z"
19
+ ],
20
+ "what_happened": "The first node suffered a GPU Xid 48 (double-bit ECC) error; Beaker cordoned it and killed the job. Beaker auto-resumed on a new node ~2.5 min later (uncharged gap). The agent received a bare 'Continue the research' prompt with no notice that the container had restarted.",
21
+ "agent_response": "Discovered the restart via ps within ~4 min, preserved finished results, resumed the eight-suite review (NEB running by 13:37Z), treated the lost kappa case as a failure penalty for that candidate rather than recomputing it; candidate was rejected on MOF anyway.",
22
+ "estimated_charged_time_lost_seconds": 600,
23
+ "work_lost": "In-flight kappa transport solve for candidate carbon-contrast-step65000 (scored as failure, not rerun); background validation workers resumed from saved cases.",
24
+ "affects_published_results": false,
25
+ "notes": "Published package unchanged (45k model at the time). No recovery notice existed yet for Beaker auto-resumes."
26
+ },
27
+ {
28
+ "kind": "4 (operator pause: API key replacement)",
29
+ "ownership": "operator",
30
+ "when_charged_seconds": 94586,
31
+ "evidence": [
32
+ "operator-pause-request.json, operator-pause.json (charged_elapsed 94586.1, remaining 78213.9, latest submission a26e1009...), recoveries/20261022T061328.596685Z/recovery.json, recovery-notice.txt",
33
+ "T2 item_4658 (L12173) training at 143k; T3 item_10 (L12203) 'last complete optimizer checkpoint is at 140k; updates through 143,514 were logged but not checkpointed'; T3 item_15 (L12211), item_26 (L12229) workers live again; LEDGER.md line 89 'schedule 3,514 updates/659.489s'",
34
+ "rollout: T3 prompt 06:16:05Z (notice delivered, 78214 s correct at that time)"
35
+ ],
36
+ "what_happened": "Operator cancelled the job at 06:10:46Z to swap the OpenAI key; all agent processes ended. Pause time and preflight were not charged; the same thread was resumed with a correct notice.",
37
+ "agent_response": "Recovery controller started from the 140k checkpoint within 94 s of the prompt; replayed 3,514 updates (659 s GPU) with audit; restored five CPU validation workers from saved cases within 3 min; verified the published package unchanged.",
38
+ "estimated_charged_time_lost_seconds": 800,
39
+ "work_lost": "3,514 training updates replayed (659 s); in-flight validation cases of 5 CPU workers (resumed from caches); dev evaluation of the interrupted segment.",
40
+ "affects_published_results": false,
41
+ "notes": "Handled correctly by the operator tooling; only the replay and recovery overhead were charged."
42
+ },
43
+ {
44
+ "kind": "6 (API capacity failures) + 5 (Codex exit killed the agent's background jobs)",
45
+ "ownership": "operator",
46
+ "when_charged_seconds": 102950,
47
+ "evidence": [
48
+ "capacity-retries.jsonl: retries at 08:35:31Z (30 s), 08:36:23Z (60 s), 08:38:10Z (120 s), 11:06:12Z (240 s), 'Selected model is at capacity'",
49
+ "trajectory turn.failed at L13293, L13301, L13306, L14460; thread.started L13294/L13302/L13307/L14461",
50
+ "T3 item_620 (L13291) training at 129.6k; T4 item_2 (L13299) progress still 129,829 at 08:36Z; T6 item_1/item_2 (L13311-13312) 'processes are no longer present'; T6 item_9 (L13324) '4,829 uncheckpointed updates will be replayed'; T6 item_52 (L13398) 'adds about 15 minutes of compute'",
51
+ "T7 item_3/item_2/item_7 (L14467-14475) 'The saved jobs have stopped again, leaving the GPU idle'; T7 item_20 (L14500) 'recovery will replay 3,602 updates'; T7 item_32 (L14521) validation recovery",
52
+ "codex.stderr 2026-10-22T11:06:10Z 'failed to record rollout items: thread ... not found' x7",
53
+ "runtime.py research(): capacity path sleeps then re-invokes codex; agent jobs were children of the Codex exec tree (T8 L17455 ps: controller sh PPID 603 under codex PID 604; only 1 of 20 Popen launches used start_new_session)"
54
+ ],
55
+ "what_happened": "Two 'model at capacity' stream failures ended Codex invocations T3 (after 2.3 h) and T6 (after 2.4 h); T4/T5 failed within seconds. Each Codex exit killed every background job the agent had launched (trainer, 5 CPU validation workers, audits) because they were children of the Codex exec tree. The runtime charged the retry sleeps (450 s) and all recovery time.",
56
+ "agent_response": "Both times: detected dead processes within 30 s, archived the interrupted log tail, replayed from the last complete optimizer checkpoint (4,829 then 3,602 updates) with numerical audits, restarted validation workers from cached cases; training resumed 08:44:37Z and 11:15:48Z (9-10 min after each failure). Agent did not know the cause ('second stop cause/timing unknown', ACTIVE.md via T6 L13743).",
57
+ "estimated_charged_time_lost_seconds": 2700,
58
+ "work_lost": "4,829 + 3,602 training updates replayed (~900 s + ~675 s GPU); GPU idle ~9 min per event; in-flight validation cases (phonon audit case, paired-audit chunk, full-suite worker cases) recomputed; last items of T6 not persisted to the rollout (7 'failed to record rollout items').",
59
+ "affects_published_results": false,
60
+ "notes": "Trigger is API-side; the process loss is amplified by the harness (child processes die with Codex) and partly by the agent not detaching its controllers with setsid/start_new_session. The agent was never told that Codex itself can restart mid-turn."
61
+ },
62
+ {
63
+ "kind": "4 (three container deaths of undetermined cause, Beaker auto-resume, no recovery record)",
64
+ "ownership": "infrastructure",
65
+ "when_charged_seconds": 138300,
66
+ "evidence": [
67
+ "attempts/004 (preflight 18:28Z Oct 22), attempts/005 (21:29Z), root preflight-result.json (00:01Z Oct 23); research-state.json attempt=6; recoveries/ has only the 06:13Z operator pause",
68
+ "rollout boundaries: last T7 record 18:23:37.97Z -> T8 prompt 18:28:27Z; last T8 record 21:26:08.5Z -> T9 21:29:17Z; last T9 record 00:00:48.8Z -> T10 00:01:48Z",
69
+ "T8 item_2/item_3/item_6 (L17115-17121): GPU idle, trainer at 107,760, checkpoint 105,000, '2,760 replayed updates'; T9 item_3/item_9 (L18157, L18168): 'Training logged update 150,000, but it had not saved that checkpoint; latest complete optimizer state is 145,000'; T9 item_42 (L18227) '>=1,120 s discarded'; T9 item_67 (L18271) 'five completed relaxation stages account for at least 9,827 seconds' (MOF case lost); T10 item_14 (L19200) '1,412 updates before the pause'; LEDGER.md line 89 and 97",
70
+ "no turn.failed before these thread.started events; runtime.py phase logic means the supervisor was killed externally (SIGTERM/SIGKILL), not crashed",
71
+ "memory: cgroup memory.max 250.7 GB (233.5 GiB); memory.current 202 GB at T7 L16716 and 188 GB at T7 L16933 (oom_kill 0 then); process RSS in T8/T9 totals ~20-25 GB (T8 L18129, T9 L18264, L18735), so most charged memory was page cache"
72
+ ],
73
+ "what_happened": "Containers 3, 4 and 5 were killed from outside at ~18:24Z, ~21:27Z and ~00:01Z (Oct 22-23) and Beaker auto-resumed each within 1-5 minutes. Cause is not recorded anywhere in the run root (no Beaker job status for recovery experiment 01M5H3WG89BKBYE4YTDW39WSGZ is archived). Each kill ended the trainer and the four CPU full-validation workers. The second kill hit at the final update (150,000) of the force-increment experiment before its checkpoint/dev evaluation were saved.",
74
+ "agent_response": "Each time: verified checkpoints, archived interrupted logs, replayed 2,760 / 5,000 / 1,412 updates with audits, restored validation workers from caches; training resumed 5.3 / 5.3 / 4.2 min after the prompt. Agent recorded these as 'operator pauses' because of the stale notice (see next incident) and therefore did not look for a memory or node cause.",
75
+ "estimated_charged_time_lost_seconds": 2930,
76
+ "work_lost": "2,760 + 5,000 + 1,412 training updates replayed (576 + >=1,120 + 338 s GPU) plus ~5 min recovery each; an unsaved 150k checkpoint and its 49-batch dev evaluation; a MOF validation case with >=9,827 s of completed CPU work; in-flight NEB/phonon/surface cases; the finite-cell data audit restarted.",
77
+ "affects_published_results": false,
78
+ "notes": "Root cause open: OOM-group kill is possible but RSS evidence argues against it; node cordon/preemption or Weka-client trouble on a 100%-full filesystem are alternatives. Beaker job records (exitCode/canceledFor) for the recovery experiment would settle it."
79
+ },
80
+ {
81
+ "kind": "5/7 (stale recovery notice: wrong cause and wrong remaining budget at three restarts)",
82
+ "ownership": "operator",
83
+ "when_charged_seconds": 138320,
84
+ "evidence": [
85
+ "runtime.py lines 570-571 read recovery-notice.txt whenever it exists; recover.py line 206 writes it; nothing deletes it (file still present at run root, mtime 06:13Z Oct 22)",
86
+ "rollout user prompts at 18:28:27Z, 21:29:17Z, 00:01:48Z each carry 'The operator paused this trial to replace its API credentials ... 78214 research seconds remain at recovery' (rollout L46608, L49677, L52702); actual remaining at those times ~34,500 / ~23,900 / ~14,750 s",
87
+ "agent believed it: T8 item_6 (L17121) 'The pause interrupted training'; T9 item_9 (L18168) 'The pause did stop the workers'; T8 item_490 (L17983) 'if the operator pauses it again'; ACTIVE.md via T9 L18295: 'The latest user message again declares 78,214 research seconds remaining at recovery; preserve that declaration rather than inferring budget from wallclock pauses'; T10 L19231 recovery plan JSON 'research_seconds_remaining_at_recovery': 78214 at 00:04Z Oct 23",
88
+ "consequence: T9 item_176 (L18451) launched a full 50k-update experiment at ~22:00Z with ~6 h left (the prior 50k run took 8.5 GPU-h, progress.json gpu_hours 8.555 at T9 L18157); at the deadline T10 item_867 (L20693) training was at 137,716/150,000 with full-suite validations mid-way; last publication change was snapshot 149340 (~21:36Z Oct 22), none in the final 6.5 h"
89
+ ],
90
+ "what_happened": "The one-off operator-pause notice was re-sent verbatim by the runtime on every later Beaker auto-resume, telling the agent (a) the stop was an operator credential pause, and (b) 78,214 research seconds remained, when 34.5k, 23.9k and 14.8k actually remained. The agent explicitly trusted the declared figure over its own wall-clock inference.",
91
+ "agent_response": "Planned as if ~21.7 h remained in each of the last three containers: committed the sole GPU to 50k-update continuations and long full-suite validations, and was still mid-training/mid-validation when the clock ran out; never scheduled a final candidate evaluation/publication for the real deadline.",
92
+ "estimated_charged_time_lost_seconds": null,
93
+ "work_lost": "Final ~9.5 charged hours (containers 4-6) were planned on false information; the broad-composition candidate (dev loss improving through 135k) never reached its eight-suite review before the deadline. Whether a correctly informed agent would have published a better package is unknowable.",
94
+ "affects_published_results": true,
95
+ "notes": "This is a runner bug, not ordinary friction: the notice text contradicted reality and overstated the budget by 44k-64k seconds. The task normally tells the agent nothing about its budget; giving it a wrong number is worse than none."
96
+ },
97
+ {
98
+ "kind": "5 (sandbox blocks the loopback socket the task's documented trainer needs)",
99
+ "ownership": "operator",
100
+ "when_charged_seconds": 370,
101
+ "evidence": [
102
+ "T1 item_39 (L77): fairchem CLI -> local_launch -> get_free_port -> socket.socket -> 'PermissionError: [Errno 1] Operation not permitted' (smoke failed at unix 1792555051 = 03:57:31Z)",
103
+ "tasks/atomistic-materials/environment/baseline/uma-s-pretrain/README.md line 19: 'fairchem -c research/pretrain/train.yaml' is the documented launch; task docker-compose network_mode 'no-network' (loopback normally available)",
104
+ "preflight-result.json ipv4_blocked true; T1 item_40 (L78) 'The standard FAIRChem launcher failed before training because it opens a local network socket, which this environment blocks'; T1 item_46 (L107) train_single.py 'Socket-free, one-GPU FAIRChem training'; rollout: failure noticed 03:58:01Z, custom runner training 04:00:53Z"
105
+ ],
106
+ "what_happened": "Our seccomp network ban denies AF_INET socket creation, so the task's reference training entry point (fairchem CLI, which binds a localhost MASTER_PORT even for one GPU) cannot run. The task's own environment only forbids external network.",
107
+ "agent_response": "Wrote a single-process trainer reusing stock FAIRChem model/collation/losses within ~3 minutes and used it for the whole run.",
108
+ "estimated_charged_time_lost_seconds": 300,
109
+ "work_lost": "None beyond the 3-5 min; the agent was forced off the reference launcher for all training (self-validated).",
110
+ "affects_published_results": false,
111
+ "notes": "Small cost here, but the same block would hit any agent that follows the baseline README literally."
112
+ },
113
+ {
114
+ "kind": "2 (persistent research mount returns EXDEV on rename/link inside /workspace/research; breaks the task's own validation driver)",
115
+ "ownership": "operator",
116
+ "when_charged_seconds": 800,
117
+ "evidence": [
118
+ "T1 item_66 (L127): /workspace/evaluation/run_local.py worker: os.rename(.../.tmp/out/run.json -> .../.tmp/run.json) 'OSError: [Errno 18] Invalid cross-device link' at 04:03Z; T1 item_71 (L135) 'physical-suite driver hit a filesystem error'; T1 item_69 (L136) run_physical_single.py 'avoids cross-directory rename'",
119
+ "T1 item_556 (L1051) optimizer snapshot os.replace EXDEV at step 20,000; T2 item_1426 (L6191) experiment-dir rename EXDEV; T2 item_2815 (L8742) os.link EXDEV; T10 item_31 (L19231) recovery-monitor rename EXDEV",
120
+ "agent notes (ACTIVE.md via T7 L14472): 'research symlink -> /run-state/workspace/research, EXDEV requires copy/hash/within-directory atomic replace'; publication-storage.json layout 'local-workspace-parent-with-persistent-research'",
121
+ "df outputs: /workspace/research on weka-aus.beaker.org/oe-adapt (T1 L40), / is overlay"
122
+ ],
123
+ "what_happened": "Renames and hard links between directories under the Weka-backed /workspace/research fail with EXDEV, so the task-provided run_local.py driver crashes mid-suite there and the agent's checkpoint/experiment bookkeeping hit the same error four more times. Preflight only checks renameat2 on the publication parent.",
124
+ "agent_response": "Wrote a wrapper around the verifier's predict routine (first validation at 04:05-04:10Z), adopted copy+hash+same-directory replace for all later moves (extra I/O for 1.7 GB checkpoints), recovered each later EXDEV failure in a few minutes.",
125
+ "estimated_charged_time_lost_seconds": 1500,
126
+ "work_lost": "First physical-suite validation partially rerun; one optimizer-snapshot capture redone; several minutes per later occurrence; recurring copy overhead for multi-GB artifacts.",
127
+ "affects_published_results": false,
128
+ "notes": "Task design assumes /workspace/research is an ordinary filesystem; our mount layout is not."
129
+ },
130
+ {
131
+ "kind": "benign",
132
+ "ownership": "benign",
133
+ "when_charged_seconds": null,
134
+ "evidence": [
135
+ "codex.stderr: 3 apply_patch verification failures (07:35Z, 09:18Z, 10:45Z Oct 21; malformed patches), 5 'write_stdin failed: Unknown process id', 5 'failed to refresh available models: request timed out'",
136
+ "T1 item_13 (L31) lmdb ReadonlyError on read-only pool, fixed next command; ModuleNotFoundError items are the agent's own scripts/threadpoolctl (T1 L175, T2 L11296, T3 L12469, T7 L15866); CUDA OOM at T2 L3741 is the agent's batch-size probe; '429' flags are numeric coincidences in JSON outputs"
137
+ ],
138
+ "what_happened": "Ordinary tool friction corrected in seconds; no charged time of note.",
139
+ "agent_response": "Corrected immediately.",
140
+ "estimated_charged_time_lost_seconds": 0,
141
+ "work_lost": "none",
142
+ "affects_published_results": false,
143
+ "notes": ""
144
+ }
145
+ ],
146
+ "environment_vs_spec": [
147
+ {"promised": "1x H100 80GB (disclosed override of 8 GPUs)", "observed": "NVIDIA H100 80GB HBM3, 1 visible, CUDA ok in all 6 preflights; gpu-access.json strict allocation /dev/nvidia7 on the last node", "evidence": "preflight-result.json, attempts/00*/preflight-result.json, gpu-access.json", "material": false},
148
+ {"promised": "22 CPUs requested", "observed": "os.cpu_count 192, sched_getaffinity 180, cgroup cpu.max 'max' (no quota); agent self-limited to small CPU slots", "evidence": "T1 item_11 (L24), T2 item_1491 (L6313), T2 item_1488 (L6310)", "material": false},
149
+ {"promised": "224 GiB RAM", "observed": "cgroup memory.max 250,720,169,984 B (233.5 GiB); peak observed memory.current 202 GB (mostly page cache); no oom_kill observed", "evidence": "T1 L40, T7 L16716, T7 L16933", "material": false},
150
+ {"promised": "/workspace/research writable ordinary filesystem for checkpoints/notes (instruction.md); verifier drivers runnable there", "observed": "Weka-backed symlink into /run-state; cross-directory rename/link -> EXDEV; task's run_local.py crashes there", "evidence": "T1 item_66 (L127), T1 L1051, T2 L6191, T2 L8742, T10 L19231", "material": true},
151
+ {"promised": "No external network (task docker-compose 'no-network'); baseline README launches training via 'fairchem -c ...'", "observed": "All AF_INET sockets denied (ipv4_blocked true), so the fairchem launcher's localhost port bind fails with EPERM", "evidence": "T1 item_39 (L77), preflight-result.json, baseline README line 19", "material": true},
152
+ {"promised": "Python 3.12, FAIRChem 2.16.0, phonopy 3.5.1, phono3py 3.30.0, scoring venv pymatgen 2023.5.10 (contract.md / Dockerfile)", "observed": "/opt/venv python3.12 with fairchem.core used throughout; scoring venv reports pymatgen 2023.5.10, numpy 1.26.4, ase 3.26.0; no ImportError/version complaint for promised packages", "evidence": "T1 L24 (/opt/venv/bin/python), T1 L2058 scoring_versions, 0 ImportError flags", "material": false},
153
+ {"promised": "Read-only data mounts pool/val/baselines", "observed": "Present and read-only (data_readonly true; lmdb ReadonlyError until opened readonly)", "evidence": "preflight-result.json, T1 L31/L35", "material": false},
154
+ {"promised": "32 GiB shared memory", "observed": "not probed by the agent; no shm errors", "evidence": "experiment.json resources", "material": false},
155
+ {"promised": "Research storage capacity", "observed": "shared Weka at 97-100% full all run (15 TB -> 2.6 TB free); no ENOSPC inside this run; inode use 8%", "evidence": "df outputs T1 L40 ... T10 L19502; attempts/*/preflight-result.json research_storage_free_bytes", "material": false}
156
+ ],
157
+ "budget_awareness": "The task deliberately tells the agent nothing about its 48 h budget, and until the pause the agent never reasoned about remaining time. The 06:16Z recovery notice correctly said 78,214 s remained (agent ACTIVE.md: 'At 08:07 approximately 71,550 seconds remain'). The same notice was then re-sent verbatim at the 18:28Z, 21:29Z and 00:01Z auto-resumes (rollout L46608/L49677/L52702) while ~34.5k, ~23.9k and ~14.75k s actually remained; the agent wrote 'preserve that declaration rather than inferring budget from wallclock' (T9 L18295) and recorded 78,214 in each recovery plan (T8 L17454, T9 L18293, T10 L19231). It also believed each kill was an operator credential pause. Bookkeeping files themselves are consistent: research-state/status elapsed 172800, attempt 6, turns 10, error null, submission sha 1f40a6af... == snapshots/149340 == publication-storage.json restored hash; the run ended at exactly 172,800 charged seconds with the submission intact (rollout last record 04:07:58Z Oct 23).",
158
+ "total_estimated_operator_caused_loss_seconds": 8830,
159
+ "verdict": "material (unfair)",
160
+ "verdict_reasoning": "The agent suffered seven interruptions in 48 h (one GPU-hardware node death, one operator key pause, two API capacity failures that killed all its background jobs, three externally-killed containers of unrecorded cause), each costing a checkpoint replay of 1.4k-5k updates, ~5-10 min of recovery, and in-flight validation work (one MOF case alone >=9,827 s); the directly charged loss is about 8,800 s plus unquantified CPU validation work. Separately, a runner bug re-sent the one-off operator-pause notice at the last three restarts, telling the agent the stop was a credential pause and that 78,214 s remained when 34.5k/23.9k/14.8k s remained; the agent explicitly trusted that figure, committed its only GPU to 50k-update experiments it could not finish, and reached the deadline mid-training with no candidate evaluated, so its final ~9.5 charged hours were planned on false information. Two environment defects also broke the task's own documented tooling (fairchem launcher blocked by the seccomp socket ban; run_local.py and bookkeeping hit EXDEV on the Weka research mount), though the agent worked around both quickly. The published package (100k model, score 31.48 on the agent's fixed panel) was never corrupted, and the agent's own publication gate means a better package is not guaranteed under fair conditions, but the trial as run is not a fair measure of a 48 h budget.",
161
+ "recommended_remedy": "targeted repair: fix runtime.py to consume/delete recovery-notice.txt after first use and to emit an accurate per-attempt notice (true cause, recomputed remaining seconds) on Beaker auto-resumes; detach or protect agent jobs from Codex exits on capacity retries (or at least inform the agent); allow loopback sockets or document the fairchem-launcher block; make /workspace/research rename-safe or warn; pull Beaker job records for experiment 01M5H3WG89BKBYE4YTDW39WSGZ to establish why containers 3-5 died. Disclose all of this with the result; rerun this task if it is used for comparative claims against runs that had one or zero interruptions.",
162
+ "open_questions": [
163
+ "Why did containers 3, 4 and 5 die (18:24Z, 21:27Z Oct 22, 00:01Z Oct 23)? Only Beaker job statuses (exitCode/canceledFor) for 01M5H3WG89BKBYE4YTDW39WSGZ can distinguish OOM-group kill (cgroup 233.5 GiB; memory.current reached 202 GB, mostly page cache) from node cordon/preemption or Weka-client failure on a 100%-full filesystem.",
164
+ "Did the 11:06:10Z 'failed to record rollout items' errors drop any T6 items from the resumed context (minor context loss on the T7 resume)?",
165
+ "Is the EXDEV behaviour specific to this Beaker Weka mount configuration (other runs on the same mount would be affected identically)?",
166
+ "How much CPU-side validation work was lost per interruption beyond the one measured MOF case (>=9,827 s)? The agent restarted workers from caches but in-flight cases were not itemized except in T9 item_67."
167
+ ]
168
+ }
reviews/fairness-20261031/per-task/crystal-structure-generation.json ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task": "crystal-structure-generation",
3
+ "run_root": "/weka/oe-adapt-default/stevenc/science-speedrun-runs/crystal-structure-generation-astra-xhigh-1h100-48h-20261020b",
4
+ "containers": 5,
5
+ "turns": 5,
6
+ "charged_seconds": 172800,
7
+ "research_state_error": null,
8
+ "container_timeline_utc": {
9
+ "C1": "2026-10-21 03:56:17 -> 2026-10-22 06:10:55, cancelled by operator (API key replacement); charged 94466.5 s; trajectory lines 3-11672",
10
+ "C2": "2026-10-22 06:17:03 -> 07:09:29, cancelled by operator (second key swap); charged +3130.3 s (97596.8); lines 11675-12274 (249 commands)",
11
+ "C3": "2026-10-22 07:12:25 -> 07:28:23, cancelled by operator (stop all runs on OPENAI_API_KEY_WEIWEI); charged +945.5 s (98542.3); lines 12277-12520 (103 commands)",
12
+ "gap1": "07:28Z Oct 22 -> 02:43Z Oct 23 uncharged (19 h 15 min)",
13
+ "C4": "2026-10-23 ~02:44 -> 11:19:07, supervisor died with ENOSPC on /run-state (storage-failure.log); charged +30908 s +14 s lost-heartbeat penalty (129450.2); lines 12523-17320",
14
+ "gap2": "11:19Z -> 21:09Z Oct 23 uncharged (~9 h 50 min)",
15
+ "C5": "2026-10-23 21:18:41 -> 2026-10-24 09:21:11, ran to the 172800 s deadline; charged +43349.8 s; lines 17323-22398",
16
+ "note": "The 'Oct 23 02:43Z' recovery folder is the restart AFTER the third pause (07:28Z Oct 22), not a fourth pause. There were 3 operator pauses (all Oct 22 within 78 minutes) + 1 storage outage = 4 recoveries. Each container ran exactly one Codex turn (turns=attempt=5, quick_turns=0); no capacity retries (no capacity-retries.jsonl)."
17
+ },
18
+ "incidents": [
19
+ {
20
+ "kind": "4 (infrastructure interruptions: operator pauses x3)",
21
+ "ownership": "operator",
22
+ "when_charged_seconds": "94466 (pause 1), 97597 (pause 2), 98542 (pause 3)",
23
+ "evidence": [
24
+ "recoveries/20261022T061314.031240Z/recovery.json + operator-pause.json (job 01M5E9G8NWJXCHCEE3D98THBPF canceled by stevenc 06:10:46Z; 'User-requested pause to replace the OpenAI API key')",
25
+ "recoveries/20261022T070943.771227Z/recovery.json (job 01M5H3W1Z17N7M8J8Q7P2A19EX canceled 07:09:21Z)",
26
+ "recoveries/20261023T024316.445934Z/recovery.json + operator-pause.json / operator-pause-request.json (job 01M5H73G8SNQM2YV38TDECYDS8 canceled 07:28:18Z; stop all runs on OPENAI_API_KEY_WEIWEI; resume_requires_new_user_instruction)",
27
+ "trajectory C1 L11088/L11216/L11435 (progress_snapshot: trials 96/97/114 entered ensemble stage at 04:19Z/04:46Z/05:13Z) and L11591 item_6293 (05:44Z: 96/97/114 'ensemble', 108 'initial' 2220/2500)",
28
+ "trajectory C2 L11717 item_22, L11732 item_30, L11768 item_49 ('All four evaluations have restarted. Hash checks passed for the 7,500 completed initial relaxations and the fourth trial's 2,448 saved records'), L11734 item_31 (agent recovery record at 06:20:27Z)",
29
+ "trajectory C3 L12310 item_18 ('All four evaluations were interrupted in the ensemble stage ... The ensemble runner has no saved per-sample checkpoint, so its interrupted work must be rerun'), L12331 item_29 (restart at 07:12:50Z, pids 947-950), L12514 item_125 ('prototyping an evaluation-only journal for future jobs, because both operator pauses discarded unfinished ensemble work'), L12518 item_127 (eval_journal/ created)",
30
+ "trajectory C4 L12547 item_13, L12635 item_59 (journal replay verified 02:49Z), L12654 item_69 ('The four full ensemble evaluations are running again' 02:51Z), L14893 item_1260 -> L14942 item_1286 (06:20-06:36Z: 'saved filename orders from before the pause no longer match the resumed evaluators' orders ... rebuilding those mappings' -> corrected for 9,975 saved returns)",
31
+ "workspace/research/volumeprior/score_volume1650_2500/report.json etc. mtimes: trial 108 06:28Z, 97 06:32Z, 96 06:42Z, 114 07:10Z on Oct 23 (the four pause-interrupted evaluations finally completed 3h38m-4h20m into C4)",
32
+ "workspace/research/recovery_20261022_0617/recovery.json, recovery_20261022_0712/, recovery_20261023_0245/, RESEARCH_STATUS.md line 11 ('resumed 96/97/108/114 had stale pre-pause filename orders')"
33
+ ],
34
+ "what_happened": "Three operator-initiated cancellations within 78 minutes on Oct 22 (06:10Z, 07:09Z, 07:28Z) to swap API keys. At pause 1 four full 2,500-structure development evaluations were in flight: trials 96/97/114 had been in the LeMat ensemble stage for 1h52m/1h25m/0h58m (about 4.25 job-hours; the pinned ensemble runner had no per-sample checkpoint, so this progress was lost outright) and trial 108 was in initial relaxation with 2,448/2,500 saved (52 redone). In C2 the agent re-verified all saved relaxation hashes and restarted the four ensemble stages (~06:21-06:25Z); pause 2 killed them ~45 min later. In C3 it restarted them again at 07:13Z; pause 3 killed them 15 min later. C2+C3 (4,075 charged s) were therefore almost entirely recovery work and discarded compute. After the 19 h uncharged gap, C4 restarted them at 02:50Z Oct 23 and they completed 06:28Z-07:10Z, occupying the first ~4 h of C4 to redo work that had been 25-50% done at pause 1. The resumed runs also produced a stale filename-order mismatch in the agent's per-structure diagnostics (official scores unaffected) that cost ~16 min to rebuild at 06:20-06:36Z.",
35
+ "agent_response": "Handled well: preserved every completed relaxation record (hash-verified 10,000 input/output pairs), wrote resume_score.py / complete_partial_relaxation.py to rerun only missing work, and after the second loss designed an evaluation 'journal' (eval_journal/, verified by exact replay at C4 start) that caches per-structure ensemble returns so later interruptions preserve ensemble progress. Kept the published package unchanged (d2d3b07e..., 1,170/2,500 = 0.468) across all three pauses. Used the remaining-seconds figure from each pause notice correctly (78,333 / 75,203 / 74,258).",
36
+ "estimated_charged_time_lost_seconds": 9500,
37
+ "work_lost": "~4.25 job-hours of ensemble-stage compute at pause 1 (trials 96/97/114), ~3 job-hours at pause 2 (4 jobs x ~45 min), ~1 job-hour at pause 3 (4 jobs x ~15 min); a 100-structure shuffle batch interrupted at 71/100 initial relaxations (resumed later from saved records). No checkpoints or publications lost. Estimate = C2+C3 wall time 4,075 s + extra C4 charged time to redo the lost ensemble progress (~13,100-15,600 s of C4 re-run minus the ~5,400-11,000 s the trials would still have needed without the pause) + ~20 min of pause-specific agent engineering (journal verification, order-mapping rebuild); range 8,000-12,000 s.",
38
+ "affects_published_results": false,
39
+ "notes": "The four delayed trials fed the 56.76% publication at 06:31Z Oct 23 (snapshot 112108) and the research chain that led to the final 66.8% publication, so the pauses delayed but did not corrupt results. Pause 2 and 3 landing 52 and 16 minutes after their predecessors converted each recovery into pure waste; a single pause would have cost roughly a third as much."
40
+ },
41
+ {
42
+ "kind": "4/3 (infrastructure interruption: shared Weka ENOSPC)",
43
+ "ownership": "infrastructure",
44
+ "when_charged_seconds": 129436,
45
+ "evidence": [
46
+ "storage-incident.json (cause 'shared Weka ENOSPC', job exited 2026-10-23T11:19:07Z, verified_publication 112108-559e69a6d63f)",
47
+ "storage-failure.log (status heartbeats normal through 11:18:13Z; OSError Errno 28 writing /run-state/research-state.json.tmp and status.json.tmp at 11:19:06Z)",
48
+ "recoveries/20261023T210859.172491Z/recovery.json (hard_stop_additional_charge_seconds 14, storage_failure_additional_charge_seconds 14, remaining 43349.8)",
49
+ "publication-storage.json (restored_from snapshots/112108-559e69a6d63f, atomic_exchange_ok true) and recoveries/.../research-state.json last_hash 559e69a6... == last snapshot before death",
50
+ "trajectory C4 L17300-L17320 items 2570-2583 (11:11-11:18Z: live_progress shows 178 ensemble 1580->1681 returns, 121 initial 1962->2013, 142 finishing initial relaxation, 209 starting; GPU 86%; no errors)",
51
+ "trajectory C5 L17324 item_1, L17328 item_2 (df: /run-state weka 440T 94% used, 30T free at 21:18Z), L17341 item_10, L17389 item_35 (recovery audit: 178 2500 initial + 1699 ensemble payloads verified; 121 2020 initial; 142 2500 initial + 10 ensemble; 209 24 initial; 'loader_order byte_name_order_exact false, explicit_list_recovery_required true'), L17416 item_50 (SESSION_20261023_2125.md written), L17527 item_110 ('All 1709 pre-pause ensemble payloads were exact cache hits')",
52
+ "workspace/research/recovery_20261023_2120/{audit.log,integrity_summary.json,recovery_actions.json,ordered_staging.py} and SESSION_20261023_2125.md ('Live work resumed 21:25')",
53
+ "agent df outputs: C1 L1755 item_926 (Oct 21: weka 440T 97% used, 14T free); the agent's whole research dir is 104 GB, so the fill was other tenants"
54
+ ],
55
+ "what_happened": "The shared Weka volume hosting /run-state (and /workspace/research) filled up; the supervisor crashed at 11:19:07Z while persisting state and the container ended, killing four in-flight full evaluations (trial 178 ensemble ~1,699/2,500; 121 initial ~2,020/2,500; 142 ensemble just started; 209 initial 24) and one 100-structure batch. The agent's own commands show normal progress to 11:18:16Z with no ENOSPC symptoms; a targeted grep of the 54 research logs written 09:30-11:30Z found no ENOSPC strings and the agent's integrity audit found no corrupt or partial committed records. Restart came 9h50m later (uncharged). The restored filesystem enumerated directories in a different order, which would have changed the pinned scorer's loader ordinals.",
56
+ "agent_response": "Verified the restored publication byte-exact (12 files, trial 108 at 1,419/2,500 = 0.5676), hashed all 10,000 input CIFs, 7,044 saved initial records and 1,709 ensemble payloads, wrote ordered_staging.py to pass the pinned scorer an explicit CIF list preserving the original ordinals (no scorer code change), re-queued the four jobs and resumed at ~21:25Z (6-7 min after start); by 21:31Z confirmed every pre-outage ensemble payload was an exact cache hit. Because the journal built after the pauses was in place, essentially no cached work was lost.",
57
+ "estimated_charged_time_lost_seconds": 1200,
58
+ "work_lost": "14 s lost-heartbeat charge; ~7 min agent recovery/audit; MLIP reloads and uncommitted in-flight per-structure work (each relaxation <=300 s) for 4 jobs, i.e. roughly 10-15 min before evaluations regained their prior rate. No cached records, checkpoints or publications lost. Range 900-1,500 s.",
59
+ "affects_published_results": false,
60
+ "notes": "The literal claim that 'earlier pauses cost more than the storage event' does not appear in trajectory.jsonl or the notes; what the agent wrote is C3 item_125 ('both operator pauses discarded unfinished ensemble work') and C5 ('All 1709 pre-pause ensemble payloads were exact cache hits'). The quantification here supports the comparison: pauses ~8 job-hours of evaluation compute + 4,075 s of throwaway container time vs. storage ~20 min, precisely because the pauses forced the agent to build the cache that made the storage outage cheap."
61
+ },
62
+ {
63
+ "kind": "5/7 (notice text: storage-recovery notice omitted the remaining-budget figure)",
64
+ "ownership": "operator",
65
+ "when_charged_seconds": 129450,
66
+ "evidence": [
67
+ "runner/beaker/recover.py: operator-pause, capacity and gpu-isolation notices include '{remaining:.0f} research seconds remain at recovery'; the storage-exhaustion notice (recovery-notice.txt in run root) says only 'The original externally enforced research budget is preserved; previous research time remains charged'",
68
+ "trajectory C5 L17416 item_50 and workspace/research/SESSION_20261023_2125.md ('External original budget remains authoritative; no new remaining-time anchor was supplied. Removed stale wall-clock countdown from live_progress.py'), SESSION_20261024_0713.md, LIVE_STATE.md",
69
+ "trajectory C4 L17315 item_2580 (agent's own countdown 43,528 s at 11:17:50Z vs true remaining 43,350 s at the 11:19:07Z death: accurate to ~3 min); RESEARCH_STATUS.md line 27 ('Recovery anchor 74258 research seconds at 2026-10-23T02:45:40UTC')"
70
+ ],
71
+ "what_happened": "After the three pauses the agent had an accurate deadline model; after the storage recovery the notice gave no figure, so the agent deliberately dropped its countdown and ran the final 43,350 charged seconds (12.0 h) without a deadline estimate.",
72
+ "agent_response": "Noted the omission explicitly, kept the submission continuously updated (published trial 142 at 66.8% at ~03:12Z Oct 24, snapshot 150761), and continued experiments to the end; was mid-experiment (tied_identity closure, trial 226 full evaluation incomplete) when the clock expired at 09:21Z.",
73
+ "estimated_charged_time_lost_seconds": 0,
74
+ "work_lost": "None measurable: trial 226's full evaluation (started 06:05Z, ~437 ensemble returns at ~09:05Z) could not have completed before the deadline even with a known deadline; final submission intact.",
75
+ "affects_published_results": false,
76
+ "notes": "Inconsistent, not wrong, information. Template fix suggested for future runs (add remaining seconds to the storage-exhaustion notice)."
77
+ },
78
+ {
79
+ "kind": "benign",
80
+ "ownership": "benign",
81
+ "when_charged_seconds": null,
82
+ "evidence": [
83
+ "codex.stderr: 7 apply_patch 'multiple operations target' (model patch formatting), 2 write_stdin 'Unknown process id' (model), 1 'failed to refresh available models: request timed out' at 2026-10-24T03:24Z (model-list refresh only)",
84
+ "trajectory: 5 'error' items = Codex use_legacy_landlock deprecation warning at each container start (L2, L11674, L12276, L12522, L17322)",
85
+ "C1 L954/L971 items 500/508 exit 139: agent's own generator segfaulted in spglib standardize_cell on a degenerate sampled cell; fixed by the agent by item_528 (L999)",
86
+ "exit 143 x41: the agent's own await_cpu_fit_budget.py wrappers and intentionally stopped probes (e.g. C4 L12581 item_20, 'I stopped it'); C3 item_28 was simply in flight at the cancel",
87
+ "ModuleNotFoundError x3 (C4 L16553/L16555 'datasets' under /opt/conda; C5 L17389 'safetensors' under /opt/lemat/.venv): interpreter-choice slips, corrected immediately; both packages exist in their intended environments per the Dockerfile",
88
+ "C1 L2134 Permission denied: the agent had chmod -R a-w its own candidate directory",
89
+ "'429' (436 hits) are numeric substrings in score outputs; regex for HTTP 429 / rate limit found 0 matches; no capacity-retries.jsonl",
90
+ "cgroup memory.events oom_kill 0 at every check (L11363, L12302, L19409); 'OOM' hits are words in the agent's notes"
91
+ ],
92
+ "what_happened": "Ordinary research friction and model-side slips; none caused by the operator setup.",
93
+ "agent_response": "Corrected within seconds to minutes.",
94
+ "estimated_charged_time_lost_seconds": 0,
95
+ "work_lost": "none",
96
+ "affects_published_results": false,
97
+ "notes": ""
98
+ }
99
+ ],
100
+ "environment_vs_spec": [
101
+ {"promised": "1x H100 80GB (operator override of task.toml gpus=8), exclusive", "observed": "NVIDIA H100 80GB HBM3, 81,559 MiB, GPU-91ac4bec only (landlock), visible_gpus 1 in all five preflights", "evidence": "gpu-access.json; preflight-result.json; attempts/00{1..4}/preflight-result.json; trajectory C1 L1755, C5 L17328", "material": false},
102
+ {"promised": "22 CPUs requested (experiment.json cpuCount 22)", "observed": "No cgroup CPU quota (cpu.max = 'max 100000'); cpu_affinity_count 180; the agent self-limited to 21-22 (score_limits.json cpu_budget 21). More than promised was available, never less", "evidence": "trajectory C1 L276 item_143, C4 L16987 item_2384, C3 L12302 item_12; preflight.jsonl", "material": false},
103
+ {"promised": "224 GiB RAM", "observed": "cgroup memory.max 250,720,169,984 B (233.5 GiB); peak observed memory.current ~144 GiB (L6378); oom_kill 0 throughout", "evidence": "trajectory L276, L6378, L11363, L16987, L19409", "material": false},
104
+ {"promised": "Dockerfile: pytorch 2.8.0-cuda12.8-cudnn9, Python 3.11, OMatG + LeMat pinned, safetensors, torch-scatter, MPS usable", "observed": "torch 2.8.0+cu128 at /opt/conda (Python 3.11); /opt/lemat/.venv scorer ran; nvidia-cuda-mps-control daemon worked for GPU sharing; no CUDA/cuDNN/NCCL errors in 9,275 commands", "evidence": "trajectory C1 L18 item_8; C3 L12316 item_21; index hit counts", "material": false},
105
+ {"promised": "mp20 train/val/manifest + scorer-assets read-only; no test split; no network", "observed": "development_data_ok, data_readonly, evaluation_roles_absent all true; network_blocked true, unix IPC ok, in every preflight", "evidence": "preflight-result.json; attempts/*/preflight-result.json", "material": false},
106
+ {"promised": "task.toml storage_mb 1,048,576 (1 TiB) writable research space", "observed": "/workspace/research -> /run-state/workspace/research on shared Weka (440 TB) that was 94-97% full for the whole trial (14 TB free Oct 21, 30 TB free Oct 23) and hit ENOSPC on Oct 23 11:19Z; agent's own usage 104 GB. Local overlay / and /tmp 14 TB, 5-8% used", "evidence": "trajectory C1 L1755 item_926, C4 L13660/L15504/L16978, C5 L17328 item_2; storage-incident.json; du of workspace/research", "material": true},
107
+ {"promised": "48 h = 172,800 charged s; recoveries resume same thread", "observed": "research-state/status/trial agree (172,800 s, attempt 5, turns 5, sha ae044a8b == snapshot 150761); all five thread.started share thread 01a15c9a-...; recovery charged_elapsed values match Beaker job durations within ~15 s; C5 Beaker timeout 45,150 s > remaining 43,350 s so no early cut", "evidence": "research-state.json, status.json, snapshots/index.jsonl, recoveries/*/operator-pause.json jobs[].status, experiment.json timeout", "material": false}
108
+ ],
109
+ "budget_awareness": "The task does not tell the agent its budget, but each of the three operator-pause notices (recover.py template) supplied the correct remaining seconds (78,333 / 75,203 / 74,258), which the agent recorded (workspace/research/recovery_20261022_0617/recovery.json; RESEARCH_STATUS.md 'Recovery anchor 74258 research seconds at 2026-10-23T02:45:40UTC; paused time excluded') and tracked accurately: its live_progress.py reported 43,528 s remaining at 11:17:50Z (C4 L17315) versus the true 43,350 s at the 11:19:07Z death. The storage-exhaustion notice omitted the figure; the agent wrote 'no new remaining-time anchor was supplied' (SESSION_20261023_2125.md, C5 L17416) and ran the final 12.04 h without a deadline model. No status-file contradictions: research-state.json, status.json and the recovery receipts are mutually consistent and the run ended at exactly 172,800 charged seconds with the submission (ae044a8b...) equal to the last snapshot.",
110
+ "caches_survived_restarts": "Yes. After pause 1: 7,500 completed initial-relaxation records (trials 96/97/114) + 2,448 of trial 108 were hash-verified and reused (C2 L11768); ensemble-stage progress was NOT cached then and was lost three times. After pause 3 the agent's eval_journal (built in C3/C4, exact-replay verified at C4 L12635) cached per-structure ensemble returns. After the storage outage: 10,000 input CIF hashes, 7,044 initial records and 1,709 ensemble payloads verified intact; all 1,699 (trial 178) + 10 (trial 142) pre-outage ensemble payloads were exact cache hits (C5 L17527 item_110; recovery_20261023_2120/integrity_summary.json). Directory enumeration order changed after the restore, worked around with an explicit CIF list (ordered_staging.py) without modifying scorer code.",
111
+ "total_estimated_operator_caused_loss_seconds": 10700,
112
+ "verdict": "minor (disclose)",
113
+ "verdict_reasoning": "Three operator-initiated API-key pauses inside 78 minutes on Oct 22 destroyed about 8 job-hours of in-flight ensemble evaluation (no per-sample checkpoint existed), made the 52-minute and 16-minute containers C2/C3 (4,075 charged s) essentially throwaway, and pushed the four decisive full-trial results from an expected ~08:00-09:00Z Oct 22 to 06:28-07:10Z Oct 23, roughly 2.5-3 h of charged time; the agent also spent ~20 min on pause-specific engineering (resume helpers, an evaluation journal, an order-mapping rebuild). The shared-Weka ENOSPC death on Oct 23 was infrastructure-caused but, thanks to that journal, cost only ~20 min and zero cached work; the restored publication matched the last snapshot byte-for-byte. The environment otherwise matched or exceeded the disclosed allocation (H100 exclusive, no CPU quota, 233 GiB cgroup, correct torch/CUDA, read-only data, no network, zero OOM kills, zero capacity retries). Total operator-caused loss is ~10,700 s (~3.0 h, ~6% of 48 h) with no lost or corrupted publication and the final 66.8% dev-score package published 6 h before the deadline, so the trial is usable with disclosure rather than unfair.",
114
+ "recommended_remedy": "disclose",
115
+ "open_questions": [
116
+ "The parent's paraphrase 'earlier pauses cost more than the storage event' is not a literal agent statement in trajectory.jsonl or the notes; closest statements are C3 item_125 (L12514) and C5 item_110 (L17527). If it came from another summary, that source should be cited instead.",
117
+ "The full-tree grep for ENOSPC strings across the 104 GB research directory did not finish (slow Weka); the targeted grep over the 54 logs written 09:30-11:30Z on Oct 23 was negative and the agent's integrity audit found no corrupt or partial records, so no corruption is indicated, but the full sweep was not completed.",
118
+ "Shared Weka was 94-97% full on every df the agent ran (Oct 21 and Oct 23); other trials in the same batch mounting /run-state on this volume share the same risk and should be checked for silent ENOSPC in background processes.",
119
+ "Whether the C5 end state (trial 226 full evaluation unfinished, frozen audit 217 consuming scorer slots) would have been scheduled differently had the storage notice included the remaining-seconds figure; not demonstrable either way."
120
+ ]
121
+ }
reviews/fairness-20261031/per-task/fruit-fly-neuron-reconstruction.json ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task": "fruit-fly-neuron-reconstruction",
3
+ "run_root": "/weka/oe-adapt-default/stevenc/science-speedrun-runs/fruit-fly-neuron-reconstruction-astra-xhigh-1h100-48h-20261022a",
4
+ "containers": 5,
5
+ "turns": 228,
6
+ "charged_seconds": 172800,
7
+ "research_state_error": null,
8
+ "container_timeline": [
9
+ {
10
+ "container": 1,
11
+ "turns": "1-19",
12
+ "charged_s": 16922,
13
+ "utc": "2026-10-22T01:28:43 -> 06:10:47",
14
+ "end": "operator pause #1 (API key replacement), SIGTERM, graceful, 0 s extra charge"
15
+ },
16
+ {
17
+ "container": 2,
18
+ "turns": "20-26",
19
+ "charged_s": 3237,
20
+ "utc": "2026-10-22T06:15:19 -> 07:09:21",
21
+ "end": "operator pause #2 (API key replacement), graceful"
22
+ },
23
+ {
24
+ "container": 3,
25
+ "turns": "27-29",
26
+ "charged_s": 992,
27
+ "utc": "2026-10-22T07:11:39 -> 07:28:19",
28
+ "end": "operator pause #3 (stop all runs on OPENAI_API_KEY_WEIWEI), graceful; 19.2 h uncharged pause"
29
+ },
30
+ {
31
+ "container": 4,
32
+ "turns": "30-71",
33
+ "charged_s": 30859,
34
+ "utc": "2026-10-23T02:43:18 -> 11:19:09",
35
+ "end": "shared Weka ENOSPC killed supervisor (storage-failure.log); +10 s heartbeat charge; 9.8 h uncharged gap"
36
+ },
37
+ {
38
+ "container": 5,
39
+ "turns": "72-228",
40
+ "charged_s": 120800,
41
+ "utc": "2026-10-23T21:09:06 -> 2026-10-25T06:53:04",
42
+ "end": "budget exhausted at exactly 172800 charged s; phase complete, error null"
43
+ }
44
+ ],
45
+ "incidents": [
46
+ {
47
+ "kind": "4 infrastructure interruption (operator pause)",
48
+ "ownership": "operator",
49
+ "when_charged_seconds": 16922,
50
+ "evidence": [
51
+ "recoveries/20261022T061340.612579Z/recovery.json (source_failure 'User-requested pause to replace the OpenAI API key', job canceled by stevenc 06:10:47Z)",
52
+ "trajectory turn 19 item_28/item_30 (full-v4 at 38-40/125 windows, 8.5M calls)",
53
+ "turn 20 item_26, item_50, item_61 (41 windows retained = 6,897,297 calls, 84 restarted)",
54
+ "workspace/research/NOTES.md lines 191-205"
55
+ ],
56
+ "what_happened": "Container 1 was cancelled by the operator to replace the API key while the agent's full-v4 development replay (4 MPS FFN workers on the one H100, started 03:39Z) was at 40/125 windows. In-flight partial windows were lost: ~8.55M calls done vs 6,897,297 retained => ~1.65M FFN calls (~1,770 s of GPU work at ~932 calls/s) discarded.",
57
+ "agent_response": "Turn 20 (06:15:42-06:22:29Z): read notes, inspected native window receipts, wrote a recovery adapter (recover_ffn_v4_operator_v1.py) that hash-verified all 41 saved windows and relaunched the 84 missing ones plus the 3 queued downstream jobs; charged 9,367 s against its own 28,800 s FFN cap. Efficient (~7 min).",
58
+ "estimated_charged_time_lost_seconds": 2200,
59
+ "work_lost": "~1.65M FFN calls of in-flight windows (recomputed); 0 publications lost (snapshot 007683-885727f7 == latest_submission at pause).",
60
+ "affects_published_results": false,
61
+ "notes": "GPU-work loss ~1,770 s + recovery turn ~430 s. Pause notice correctly reported 155,878 s remaining."
62
+ },
63
+ {
64
+ "kind": "4 infrastructure interruption (operator pause)",
65
+ "ownership": "operator",
66
+ "when_charged_seconds": 20159,
67
+ "evidence": [
68
+ "recoveries/20261022T070951.315614Z/recovery.json (job canceled by stevenc 07:09:21Z)",
69
+ "turn 26 item_8/item_12 (46 windows complete, 2.79M new calls since restart, 16 windows active)",
70
+ "turn 27 item_10, item_29, item_38",
71
+ "NOTES.md lines 217-225 (retained calls 6,897,297 -> 7,025,268; +3,181 s charged to FFN cap)"
72
+ ],
73
+ "what_happened": "Container 2 was cancelled 54 min after the first recovery, again for key replacement. Recovery-1 had made ~2.8M new FFN calls but only 5 small windows (127,971 calls) completed; the 16 large in-flight windows were lost again => ~2.69M calls (~2,885 s GPU) discarded.",
74
+ "agent_response": "Turn 27 (07:11:57-07:16:38Z): verified 46 windows, wrote recovery v2, relaunched 79 windows and the downstream queue (~5 min).",
75
+ "estimated_charged_time_lost_seconds": 3185,
76
+ "work_lost": "~2.69M FFN calls (almost the entire container-2 GPU output) recomputed later.",
77
+ "affects_published_results": false,
78
+ "notes": "Pause notice reported 152,641 s remaining (recorded by agent in NOTES.md line 219)."
79
+ },
80
+ {
81
+ "kind": "4 infrastructure interruption (operator pause)",
82
+ "ownership": "operator",
83
+ "when_charged_seconds": 21150,
84
+ "evidence": [
85
+ "recoveries/20261023T024317.979978Z/recovery.json + operator-pause.json (reason: stop all runs using OPENAI_API_KEY_WEIWEI; canceled 07:28:19Z)",
86
+ "turn 29 item_16 (721,060 calls since recovery, no completed window)",
87
+ "turn 30 item_8, item_18 (46 windows retained, 79 restarted, 15,231 s left of FFN cap)",
88
+ "NOTES.md lines 233-241 (recovery 2 stopped at 840 s with no new window)"
89
+ ],
90
+ "what_happened": "Container 3 was cancelled 17 min after start (third key-related stop); recovery-2 had run 840 s with no completed window, so all of it was lost. Trial then sat paused (uncharged) 19.2 h until 2026-10-23T02:43Z.",
91
+ "agent_response": "Turn 30 (02:45:16-02:49:37Z): re-verified 46 windows, recovery v3, relaunched (~4.5 min). The agent's own cap accounting now charged 13,569 s of its 28,800 s FFN cap to the three interruptions; the v4 replay still completed within the cap (NOTES.md line 342: 125/125, no time-limited window, 2026-10-23T06:06:51Z).",
92
+ "estimated_charged_time_lost_seconds": 1120,
93
+ "work_lost": "~780k FFN calls (840 s GPU) recomputed; nothing published lost.",
94
+ "affects_published_results": false,
95
+ "notes": "Three operator-initiated kills within 78 minutes of the same long replay; avoidable with a single key swap."
96
+ },
97
+ {
98
+ "kind": "4 infrastructure interruption (storage outage) + 3 resource shortfall (ENOSPC)",
99
+ "ownership": "infrastructure",
100
+ "when_charged_seconds": 51999,
101
+ "evidence": [
102
+ "storage-incident.json, storage-failure.log (OSError Errno 28 writing /run-state/research-state.json.tmp at 11:19:08Z)",
103
+ "turn 1 item_41 (df: /run-state weka 440T used 432T, 99% at trial start; /workspace/research lives on that mount)",
104
+ "turn 70 item ~L1316 (df 440T/440T, 112G avail at ~10:30Z) and agent message 'free space is falling beyond what this run has written'",
105
+ "turn 71 item_59 (storage available_GiB 30.995 at 11:16:58Z; v5 at 28/125 windows, 6,602,440 model_windows calls)",
106
+ "turn 72 item_15, item_24, item_35 (28 windows = 5.12M calls retained, 97 recomputed, 7,442 s charged to FFN cap; staged package /workspace/submission-full-trial-v5 missing, restored from protected copy)",
107
+ "attempts/00[1-4]/preflight-result.json research_storage_free_bytes: 8044, 6589, 6317, 2359 GiB (preflight did not block at 2.3 TiB free)"
108
+ ],
109
+ "what_happened": "Shared Weka (also hosting the agent's persistent /workspace/research) filled up; the supervisor died at 11:19:09Z. The agent's full-v5 replay (started ~09:18Z, 4 GPU workers) was 2.0 h in with 28/125 windows; ~1.5M in-flight calls (~1,700 s GPU) were lost, the container-local staged package was lost, and 97 windows had to be recomputed in container 5. Before the crash the agent spent part of turns 70-71 on storage-capacity workarounds (deduplicating 40.8 GiB of v4 predictions, a 20 GiB->1.9 GiB archive-compression benchmark, capacity checks in its controller).",
110
+ "agent_response": "Turn 72 (21:19:51-21:26:13Z): verified restored package hash, hash-checked all 28 windows, restored the staged package from research/run/full-trial-v5/model, relaunched 97 windows (~7 min). v5 later completed with 0 capped windows and was promoted (jobs/full-development-v5/exit.json: nERL 0.005778 vs 0.005594, snapshot 077392).",
111
+ "estimated_charged_time_lost_seconds": 3400,
112
+ "work_lost": "~1.5M FFN calls recomputed; staged package dir (recovered byte-identically); no snapshot/publication lost (restored 885727f7 == latest at death).",
113
+ "affects_published_results": false,
114
+ "notes": "GPU loss ~1,720 s + recovery turn ~450 s + storage workaround ~1,200 s + 10 s heartbeat. Notice text was accurate; it did not state remaining seconds (pause notices did)."
115
+ },
116
+ {
117
+ "kind": "5 runner interference (background processes die at turn end)",
118
+ "ownership": "operator",
119
+ "when_charged_seconds": 4200,
120
+ "evidence": [
121
+ "codex.stderr 2026-10-22T02:39:06 'failed to record rollout items: thread not found' and 02:39:17 'write_stdin failed: Unknown process id 3022'",
122
+ "NOTES.md lines 91-95 ('At 02:39 UTC ... full-v2 controller 2728 and parent shell had disappeared; FFN launcher 2760 and four workers survived under orphaned process group 2759. Session 3022 was gone ... Last progress: 3/125 windows, 890,924 calls')",
123
+ "turn 2 item_12 (agent stops and archives the orphaned attempt), item_18 (launches detached research_job.py controller)"
124
+ ],
125
+ "what_happened": "Each runtime turn is a separate `codex exec resume` process; when turn 1 ended normally, the Codex exec session and the agent's background full-v2 pipeline controller were killed (workers orphaned). The agent was not warned about this behaviour.",
126
+ "agent_response": "Diagnosed within ~3 min (02:38:49-02:41:30Z), archived the attempt as interrupted, and from then on ran all long jobs through a setsid 'research_job.py' detached controller. Later 'write_stdin failed: Unknown process id' errors (Oct 24 05:05, 23:52; Oct 25 02:10, 02:57, 03:46, 04:02) only killed read-only observer sessions (turns 101/201/211/214/217/219 confirm all jobs live).",
127
+ "estimated_charged_time_lost_seconds": 1150,
128
+ "work_lost": "full-v2 replay at 3/125 windows (890,924 FFN calls, ~955 s GPU); abandoned rather than recomputed because v3/v4 superseded it.",
129
+ "affects_published_results": false,
130
+ "notes": "Arguably shared responsibility (agent launched without setsid), but the per-turn process model is ours and undocumented to the agent."
131
+ },
132
+ {
133
+ "kind": "2 data/mount defect (cross-directory rename returns EXDEV on research mount)",
134
+ "ownership": "operator",
135
+ "when_charged_seconds": 2600,
136
+ "evidence": [
137
+ "turn 1 item_85 (early_gate.log: Triton cache write 'Invalid cross-device link' ... -> /workspace/research/cache/triton/...)",
138
+ "turn 1 item_87 (agent probe: 'same parent rename passed; cross parent [Errno 18] Invalid cross-device link ... devices 3700557221 3700557221')",
139
+ "turn 1 item_86/item_88 (agent message; local_triton_cache.py added)",
140
+ "turn 1 item_41 (df shows /workspace/research on weka /run-state)"
141
+ ],
142
+ "what_happened": "The persistent research directory (Weka) rejects rename() across parent directories even on the same device, which broke Triton's default kernel-cache commit and crashed the agent's first reconstruction probe.",
143
+ "agent_response": "Wrote a local Triton cache shim and moved caches; re-ran the probe. ~15 items inside turn 1.",
144
+ "estimated_charged_time_lost_seconds": 400,
145
+ "work_lost": "one short smoke probe rerun",
146
+ "affects_published_results": false,
147
+ "notes": "Minor; the same quirk is why the agent later noted the workspace is reachable via two paths (/workspace/research and /run-state/workspace/research)."
148
+ },
149
+ {
150
+ "kind": "benign",
151
+ "ownership": "benign",
152
+ "when_charged_seconds": null,
153
+ "evidence": [
154
+ "codex.stderr (3x 'missing field cmd' = model malformed tool call; models-cache parse error 2026-10-23T03:23; models refresh timeout 2026-10-24T16:55 with turn 164 starting 21 s after turn 163)",
155
+ "no capacity-retries.jsonl; quick_turns 0",
156
+ "traj index: 228 error items all the use_legacy_landlock deprecation notice",
157
+ "flagged commands: 'Permission denied' = reading /proc/<pid>/fd of other processes (T49 item_20, T201 item_128); 'OOM' matches are the agent's own notes stating OOM-kill 0"
158
+ ],
159
+ "what_happened": "No API capacity retries, stream errors, OOM kills, CUDA/driver errors, missing packages or network blocks beyond the contracted no-network sandbox.",
160
+ "agent_response": "n/a",
161
+ "estimated_charged_time_lost_seconds": 0,
162
+ "work_lost": "none",
163
+ "affects_published_results": false,
164
+ "notes": "Agent spent ~10 min (turns 165-173) releasing page cache because measured cgroup memory reached 233.5 GiB against the stated 224 GiB request; no OOM occurred (NOTES.md line 891), so this is caution, not a shortfall. The '200 GB development-storage guard' hit in turn 166 is the task's own runtime code (upstream/pathfinder/fetch_axonem.py LIMIT=200_000_000_000), task-design not operator."
165
+ }
166
+ ],
167
+ "environment_vs_spec": [
168
+ {
169
+ "promised": "1x H100 (operator override of task's 8 GPUs)",
170
+ "observed": "1x NVIDIA H100 80GB HBM3, driver 570.124.06, CUDA 12.8; MPS with 4 workers worked throughout",
171
+ "evidence": "turn 1 item_5 nvidia-smi 01:29:03Z; gpu-access.json strict_allocation; preflight-result.json visible_gpus 1",
172
+ "material": false
173
+ },
174
+ {
175
+ "promised": "22 CPUs requested",
176
+ "observed": "cpu_affinity_count 180 (agent self-limited to taskset -c 3-24)",
177
+ "evidence": "preflight-result.json; jobs/full-development-v5-failed-publication-stage-v1/controller.log affinity list",
178
+ "material": false
179
+ },
180
+ {
181
+ "promised": "224 GiB RAM requested",
182
+ "observed": "cgroup memory.current reached 233.5 GiB (file cache) with OOM-kill 0; host shows 2.0 TiB",
183
+ "evidence": "NOTES.md line 891; turn 1 item_5 free -h",
184
+ "material": false
185
+ },
186
+ {
187
+ "promised": "task.toml storage_mb 1,048,576 (1 TiB) writable research storage",
188
+ "observed": "research dir is on shared Weka that was 99% full at trial start (7.9T free of 440T), fell to 112 GiB then 31 GiB free, then ENOSPC killed container 4; preflights ran at 8.0/6.6/6.3/2.3 TiB free",
189
+ "evidence": "turn 1 item_41; turn 70-71 df and status JSON; storage-failure.log; attempts/*/preflight-result.json",
190
+ "material": true
191
+ },
192
+ {
193
+ "promised": "Dockerfile python:3.11.13-slim, pinned requirements.lock (torch, triton, kimimaro...)",
194
+ "observed": "/usr/local/lib/python3.11 torch+triton present; no ModuleNotFoundError for task deps (single ModuleNotFoundError in T1 item_239 is the agent's own script log)",
195
+ "evidence": "tracebacks in turn 1 item_85; flagged-command index",
196
+ "material": false
197
+ },
198
+ {
199
+ "promised": "no network (contract/task.toml)",
200
+ "observed": "network_blocked true, unix IPC ok; agent never needed network",
201
+ "evidence": "preflight-result.json",
202
+ "material": false
203
+ },
204
+ {
205
+ "promised": "read-only data mounts training/validation/runtime; FPS kernel built for H100",
206
+ "observed": "development_mounts present, data_readonly true, fps_cuda_abi_ok true; gpu-check passed",
207
+ "evidence": "preflight-result.json; remaining-preparation-20261022a/.../gpu-check.json",
208
+ "material": false
209
+ },
210
+ {
211
+ "promised": "persistent research files survive restarts",
212
+ "observed": "true, but /workspace/research rejects cross-directory rename (EXDEV) and container-local /workspace/submission-* staging dirs are lost on restart (agent re-created from protected copies)",
213
+ "evidence": "turn 1 item_87; turn 72 item_15",
214
+ "material": false
215
+ }
216
+ ],
217
+ "budget_awareness": "By task design the agent is not told the 48 h budget (task.toml comment) and CONTINUE prompts carry no remaining-time figure. The three key-replacement notices did state remaining seconds (155,878 / 152,641 / 151,649; recorded verbatim in NOTES.md lines 219/235) and these matched research-state.json; the storage-recovery notice omitted the figure. The agent never reasoned about global remaining time in any of 2,838 messages (only per-stage FFN caps), launched a 9,000 s CPU job at 06:52:55Z nine seconds before cutoff, and its v10 full replay was at 3/125 windows at the end. No contradiction between status files: research-state/status/trial agree (elapsed 172800, attempt 5, turns 228, error null) and the frozen submission's four files sha256-match snapshot 164218-6f223ba6 (package.json 87b4d5ec..., published 2026-10-25T04:29:31Z as full v8, nERL 0.0076677).",
218
+ "total_estimated_operator_caused_loss_seconds": 11455,
219
+ "verdict": "minor (disclose)",
220
+ "verdict_reasoning": "The trial reached the full 172,800 charged seconds with an intact, snapshot-verified submission, and no environment/package/GPU defect was found. However, four operator-side container deaths occurred: three operator-initiated API-key pauses within 78 minutes on Oct 22 that each killed the same long single-GPU full replay (losing ~1.65M, ~2.69M and ~0.78M in-flight FFN calls), and the Oct 23 shared-Weka ENOSPC that killed the v5 replay at 28/125 windows after 2 h (~1.5M calls lost, 97 windows recomputed, staged package lost). Adding the turn-boundary kill of the full-v2 replay, the EXDEV Triton workaround and pre-outage storage workarounds, about 11,400 charged seconds (~3.2 h, 6.6% of the budget) of GPU work and re-verification were operator-caused; the agent's recoveries were fast (4-7 min each) and byte-verified. The published v8 package was not corrupted and the next candidate (v10) could not have completed even with the lost time returned, so published results are not affected, but the loss is well above ordinary friction and should be disclosed.",
221
+ "recommended_remedy": "disclose",
222
+ "open_questions": [
223
+ "Whether a ~6.6% charged-time loss with no effect on the published package meets this review's threshold for 'material' rather than 'minor'.",
224
+ "Whether the operator's preflight should have refused to start container 4 at 2.3 TiB shared free space given the trial's own ~228 GB research footprint plus other concurrent runs.",
225
+ "Exact calls at the moment of each kill are interpolated from the last status heartbeat (<=3 min before death); losses could be ~5% higher."
226
+ ]
227
+ }
reviews/fairness-20261031/per-task/molecular-pretraining-transfer.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task": "molecular-pretraining-transfer",
3
+ "run_root": "/weka/oe-adapt-default/stevenc/science-speedrun-runs/molecular-pretraining-transfer-astra-xhigh-1h100-48h-20261023a",
4
+ "containers": 8,
5
+ "turns": 9,
6
+ "charged_seconds": 172800,
7
+ "research_state_error": null,
8
+ "completion_correction": "Original end-of-run state was phase=failed, error='No runnable infer.sh was published' (completion-correction/original-research-state.json, original-status.json; Beaker job 01M5WS4ZB8G7VP1ZYTZAB7X1AM exitCode 1 at 2026-10-26T21:03:16Z). The launcher's post-budget check looked for infer.sh, but this task's contract requires encoder.json + checkpoint.pt (runtime.py submission_entrypoint(); molecular_completion.py docstring: 'The old launcher incorrectly rejected an otherwise captured cutoff package'). The correction (receipt.json, schema molecular-cutoff-entrypoint-correction/v1, applied ~22:58 UTC Oct 26) restored /run-state/submission from snapshot 103193-4fdb6e6246f5 (sha256 4fdb6e62... == research-state.last_hash), set phase=complete, error=null, additional_research_seconds=0. It did NOT affect the agent: the check runs only after the clock stops; the trajectory contains no prompt or output telling the agent about infer.sh (the single 'infer.sh' mention is the agent reading the task file /workspace/evaluation/protocol/infer.sh, container 2 item_2897).",
9
+ "incidents": [
10
+ {
11
+ "kind": "4 infrastructure interruption (operator pause)",
12
+ "ownership": "operator",
13
+ "when_charged_seconds": 85,
14
+ "evidence": [
15
+ "operator-pause.json (recorded 2026-10-23T02:48:06Z, canceled by stevenc, exit 143)",
16
+ "operator-pause-request.json",
17
+ "recoveries/20261024T202752.282731Z/recovery.json (charged_elapsed_seconds 85.1, remaining 172714.9)",
18
+ "recovery-notice.txt",
19
+ "rollout user prompt 2026-10-24T20:30:01Z (first delivery of the notice)",
20
+ "trajectory container 1 items item_1..item_15 (lines 1-30)"
21
+ ],
22
+ "what_happened": "Original container ran 85 s (agent had read the contract and just launched train_smoke.sh) before the operator cancelled it to reduce the queued-task set / replace the API key. Resumed 2026-10-24T20:27Z in a new experiment (01M5QSJCAZ9GTSK9FCVP7WQ65A) with the same thread and a correct notice (172715 s remain).",
23
+ "agent_response": "Re-read notes/contract and restarted the smoke run (container 2 item_1-item_6); no confusion.",
24
+ "estimated_charged_time_lost_seconds": 250,
25
+ "work_lost": "A just-started smoke training run; negligible.",
26
+ "affects_published_results": false,
27
+ "notes": "Pause itself was uncharged (45 h offline); only the 85 s before it plus a few minutes of re-orientation were charged."
28
+ },
29
+ {
30
+ "kind": "4 infrastructure interruption (six unplanned container restarts inside the resumed experiment)",
31
+ "ownership": "infrastructure",
32
+ "when_charged_seconds": [
33
+ 69814,
34
+ 112800,
35
+ 122900,
36
+ 134900,
37
+ 155800,
38
+ 166100
39
+ ],
40
+ "evidence": [
41
+ "trajectory.jsonl thread.started at lines 10838, 17809, 18736, 20130, 21865, 22851 (item ids reset to item_0 at each)",
42
+ "attempts/002..007 preflight mtimes (Oct 25 15:54Z, Oct 26 03:53Z, 06:48Z, 10:11Z, 16:04Z) and run-root preflight-result.json (19:12Z); research-state.json attempt=8",
43
+ "rollout user prompts at 2026-10-25T15:54:38Z, 10-26T03:53:32Z, 06:48:55Z, 10:11:27Z, 16:04:26Z, 19:12:18Z",
44
+ "results/agent-activity-20261026/accounting-checks.json: attempt 2 ended 1792943529 (15:52:09Z), attempt 3 started 1792943678 (149 s gap)",
45
+ "completion-correction/receipt.json job_status: last job created 18:56:45Z, scheduled 19:10:01Z, started 19:12:07Z (container 7 died ~18:56Z)",
46
+ "codex.stderr 2026-10-26T19:12:26 write_stdin failed: Unknown process id 80872/17252",
47
+ "GPU UUID changed every container: a85d7506 (c2), 74db2bd3 (c3), 3452b743 (c4), ca5b232f (c6), b4b531af (c8, gpu-access.json)",
48
+ "agent notes: NOTES.md:1877 (15:57Z 'Operator pause killed all prior processes; /tmp corpus cache absent'), STATUS.md:446-449 ('operator/container restart ended ALL processes'), STATUS.md:556 (06:56Z recovery2), :702-707 (10:23Z 'SECOND infrastructure recovery'), :789-793 (16:04Z 'operator reset confirmed'), :843-845 (19:15Z 'Operator recovery1912'); container 3 item_10/item_24; container 8 item_8",
49
+ "container 3 tail (line 17808): 120-expanded run at num_updates=5000 and two fine-tunes launched 03:47:34Z just before death; container 5 tail (line 20126): fresh30k at 24,800 at 10:08:08Z; container 6 tail: serial13 at 20,700 at 16:00:14Z; container 7 tail: fine-tunes at epoch 3-4 at 18:55:41Z"
50
+ ],
51
+ "what_happened": "The Beaker job was killed and auto-resumed six times (each time on a different node/GPU). Every restart killed all agent processes (GPU pretraining run, the two concurrent fixed fine-tunes, CPU caches/controllers) and wiped the container-local /tmp, including the agent's verified ~200 GB local LMDB corpus copy (built in container 2 because 'storage waits remain substantial' on the Weka mount, container 2 item_2080). Work lost: R1 (15:52Z Oct 25) 700 updates of the 180k run + 2 fine-tunes; R2 (03:51Z Oct 26) ~5,000 updates of the 120-expanded 30k run (launched 03:36:58Z, restarted from scratch 04:06:29Z) + 2 fine-tunes; R3 (~06:45Z) >=1,700 parity updates (STATUS.md:637) + Efflux/MPPB fine-tunes; R4 (~10:08Z) 1,000 fresh30k updates + alpha/CV fine-tunes; R5 (~16:00Z) 700 serial13 updates; R6 (~18:56Z) two fine-tunes at epoch 6/15 + an unsaved CPU feature extraction. Before the GPU trainer could resume, the agent had to re-copy and hash-verify the corpus each time (resume at 04:06:29Z, 06:58:03Z, 10:21:42Z, ~16:12Z, 19:19Z; R1 main resumed after 16:05Z), and spent 15-30 min per restart auditing checkpoints/process identities and re-creating its controllers (recovery_20261025_1554, recovery_20261026_0353/_0652/_1011/_1604/_1912).",
52
+ "agent_response": "Handled carefully: archived interrupted logs, verified checkpoints, restored the corpus, replayed interrupted fixed fine-tunes from scratch (protocol has no resumable fine-tune), never duplicated jobs, never fabricated results. It mis-attributed every restart to an 'operator pause' because of the re-delivered notice (see next incident).",
53
+ "estimated_charged_time_lost_seconds": 7200,
54
+ "work_lost": "About 9,100 pretraining updates re-run (~35 min GPU), ~10 interrupted fine-tunes replayed (~40 min of shared-GPU time), six corpus restores (~60 min GPU-idle for the main trainer), plus ~1.5 h of agent attention on recovery bookkeeping (partly overlapping). Each restart also added a 10 s heartbeat penalty (runtime.py load_research_state).",
55
+ "affects_published_results": false,
56
+ "notes": "Gaps between death and replacement (2-13 min) were not charged. The cause of the deaths is not recorded in the run root (only the final job is in receipt.json; no recovery folders because autoResume kept the same experiment). Last publication (snapshot 103193 = 01:11Z Oct 26) predates R2-R6; every later candidate (restart120, 120-expanded, readout, parity, similarity, fresh30k) was rejected by the agent's own full-24 reviews (STATUS.md:672, 692, 732, 757; CURRENT.md:103-106), so the restarts delayed but did not change the published package."
57
+ },
58
+ {
59
+ "kind": "5/7 runner prompt problem: stale recovery notice with wrong remaining-budget re-delivered on every restart",
60
+ "ownership": "operator",
61
+ "when_charged_seconds": [
62
+ 69814,
63
+ 112800,
64
+ 122900,
65
+ 134900,
66
+ 155800,
67
+ 166100
68
+ ],
69
+ "evidence": [
70
+ "runner/beaker/runtime.py lines 570-571 (notice read from STATE/recovery-notice.txt at every research() start) and 629-631 (appended to the first prompt of each container); file is never removed: recovery-notice.txt still present (mtime Oct 24 13:27 PDT)",
71
+ "rollout user prompts at 2026-10-25T15:54:38Z, 10-26T03:53:32Z, 06:48:55Z, 10:11:27Z, 16:04:26Z, 19:12:18Z each contain verbatim: 'The operator paused this trial to replace its API credentials ... 172715 research seconds remain at recovery.'",
72
+ "agent record container 3 (rollout L28382, 16:03Z Oct 25): STATUS.md header 'User reported172715 research seconds remaining at latest operator recovery15:54UTC' (true remaining ~102,980 s)",
73
+ "workspace/research/recovery_20261026_1912/infrastructure_interruption.json (19:13:28Z): 'reason': 'Operator-reported credential pause', 'research_seconds_remaining_as_reported': 172715 (true remaining ~6,590 s)",
74
+ "CURRENT.md (20:48/20:55Z): 'CONTINUOUS RESEARCH, no final handoff'; plan = three 30k-update arms + 3x24 fine-tunes + joint review before any publication, with ~15 min of budget left"
75
+ ],
76
+ "what_happened": "The one-time pause notice (correct on 2026-10-24) was appended again to the agent's prompt at all six unplanned restarts, telling it (a) that the operator had paused it for a credential swap (false) and (b) that 172,715 research seconds remained (false: 102,980 / 60,000 / 49,900 / 37,900 / 17,000 / 6,650 s actually remained). The runtime itself gives no other remaining-time information.",
77
+ "agent_response": "Believed it: it logged each restart as an operator pause and, at least twice, explicitly recorded 172715 s as the remaining budget. Its earlier correct budget reasoning (NOTES.md:1712 at 12:14Z Oct 25: 'fits remaining ~32h'; container 2 item_4827/item_5496) was never repeated after the first restart. In its last 1.8 h it started a multi-hour three-arm experiment that could not finish (the training was at 4,100/30,000 updates when the clock stopped).",
78
+ "estimated_charged_time_lost_seconds": null,
79
+ "work_lost": "No artifact lost. The final ~100 charged minutes were spent on an experiment that could never complete under the real deadline; under the 'there is no end point' design that is expected behavior, so it is not counted as operator loss, but the agent's decisions in that window were made on false information.",
80
+ "affects_published_results": false,
81
+ "notes": "task.toml says the agent 'is not told' its budget, yet the runner told it a (wrong) number six times. The one-time (capacity-retry) re-prompt at 20:51:47Z correctly carried only the CONTINUE text. Fix for future runs: consume/rename recovery-notice.txt after first use, or regenerate it with the true remaining seconds at each container start."
82
+ },
83
+ {
84
+ "kind": "6 API-side failure charged to the clock (model at capacity)",
85
+ "ownership": "infrastructure",
86
+ "when_charged_seconds": 172080,
87
+ "evidence": [
88
+ "capacity-retries.jsonl (unix 1793047876.96 = 2026-10-26T20:51:16Z, turn 8, retry 1, delay 30 s)",
89
+ "trajectory.jsonl line 23704 turn.failed 'Selected model is at capacity', line 23705 thread.started (container 8, second Codex process)",
90
+ "codex.stderr 2026-10-26T20:54:24 write_stdin failed: Unknown process id 18591",
91
+ "CURRENT.md:1-3 'RECOVERY 20:55: prior18591 ended with unknown terminal; no checkpoint before1600 logged updates'; STATUS.md:885, :889; container 9 item_3 (production_launch.json 20:48:20Z actual_exec_session 18591)"
92
+ ],
93
+ "what_happened": "Codex exited on an OpenAI capacity error; the runtime slept 30 s (charged) and relaunched the thread. Because the agent ran its production trainer inside a Codex exec_command session (18591), the Codex exit also killed the trainer at ~1,600 updates before its first checkpoint.",
94
+ "agent_response": "Detected the dead session within ~3 min, preserved logs, relaunched the exact recipe (session 81594) at 20:55Z, verified the 2k checkpoint at 20:59Z, reached 4,100 updates by 21:03Z (budget end).",
95
+ "estimated_charged_time_lost_seconds": 450,
96
+ "work_lost": "~1,600 pretraining updates (~3 min) + 30 s retry + ~4 min recovery, in the final 12 minutes.",
97
+ "affects_published_results": false,
98
+ "notes": "Only capacity event of the run."
99
+ },
100
+ {
101
+ "kind": "benign/unattributed: unexplained SIGTERM to one trainer mid-container",
102
+ "ownership": "benign",
103
+ "when_charged_seconds": 92200,
104
+ "evidence": [
105
+ "container 3 item_1909 (agent message: 'ended unexpectedly with SIGTERM near 9,800 updates'), item_1912 (record: observed_exit 143, cause 'Unknown; no requested stop or agent signal', saved 9000, logged 9800, original_session 84190, cgroup oom_kill 0)",
106
+ "STATUS.md:213 'Original unexplained SIGTERM143 at ~9800; recovered 9k then finished 10k'"
107
+ ],
108
+ "what_happened": "At 2026-10-25T22:11Z the response-arm trainer (launched inside Codex exec session 84190) received SIGTERM with no container restart, no OOM and no agent kill. Possibly Codex exec-session lifecycle; could not be attributed from the run root.",
109
+ "agent_response": "Resumed from the 9,000-update checkpoint with the same recipe, recorded the FP16-resume caveat.",
110
+ "estimated_charged_time_lost_seconds": 450,
111
+ "work_lost": "800 updates (~2.5 min) plus resume/audit time; one matched-comparison arm carries a documented restart caveat.",
112
+ "affects_published_results": false,
113
+ "notes": "Not counted in the operator total. The other 44 exit-143 commands are the agent's own foreground monitors/drivers killed by the Codex tool timeout (e.g. container 2 item_14, item_947, item_2250), a model-side pattern."
114
+ },
115
+ {
116
+ "kind": "7 budget/bookkeeping error after the clock stopped (wrong entrypoint check)",
117
+ "ownership": "operator",
118
+ "when_charged_seconds": 172800,
119
+ "evidence": [
120
+ "completion-correction/original-research-state.json (phase failed, error 'No runnable infer.sh was published')",
121
+ "completion-correction/receipt.json (job 01M5WS4ZB8G7VP1ZYTZAB7X1AM exitCode 1; snapshot 103193-4fdb6e6246f5; required_entrypoint encoder.json; additional_research_seconds 0)",
122
+ "runner/beaker/runtime.py research(): 'if not (src / submission_entrypoint()).is_file(): failure = ... No runnable ...'",
123
+ "runner/beaker/molecular_completion.py docstring",
124
+ "publication-storage.json restored_sha256 4fdb6e62... == research-state.last_hash; submission/ contains encoder.json, checkpoint.pt, user_dir/"
125
+ ],
126
+ "what_happened": "The launcher image's end-of-run check demanded infer.sh for a task whose contract specifies encoder.json, so the completed trial was recorded as failed and the Beaker job exited 1. Corrected post hoc by molecular_completion.py without rerunning research.",
127
+ "agent_response": "None; the agent never saw it (check runs after stop_research()).",
128
+ "estimated_charged_time_lost_seconds": 0,
129
+ "work_lost": "None; the cutoff package was captured intact.",
130
+ "affects_published_results": false,
131
+ "notes": "Pure bookkeeping; the restored submission hash equals the last snapshot."
132
+ },
133
+ {
134
+ "kind": "benign: environment signals checked and dismissed",
135
+ "ownership": "benign",
136
+ "when_charged_seconds": null,
137
+ "evidence": [
138
+ "GPU OOM in the agent's own compact_calibrated30k run (container 2 item_1216, oom_restart20 record item_1228) at its chosen batch; cgroup memory.events oom_kill 0 at every read (container 2 item_978, item_1516, item_1740, item_2319, item_3072; container 3 item_1367, item_2180, item_2321; container 5 item_167)",
139
+ "ModuleNotFoundError: matplotlib (container 2 item_146, item_1829, item_3373, item_3671, item_4626, item_5070; container 3 item_1453; container 5 item_262; container 7 item_203) - not in the task Dockerfile; agent rendered figures with Pillow (STATUS.md:662)",
140
+ "ModuleNotFoundError unimol2/tasks (container 2 item_1083, container 3 item_2317, item_3322) - path/user-dir usage, matches Dockerfile (Uni-Mol is cloned, not pip-installed)",
141
+ "exit 127: rsvg-convert, py-spy, gdb absent (container 2 item_3376; container 5 item_170/171) - not promised",
142
+ "Permission denied: rg over /run-state root-owned dirs while searching for AGENTS.md (container 6 item_711)",
143
+ "codex.stderr: 1 apply_patch verification failure (model-side stale patch), 1 'failed to refresh available models: request timed out', 7 write_stdin-to-dead-session errors (consequence of restarts)",
144
+ "preflight.jsonl item_0 '[features].use_legacy_landlock is deprecated' at every start (harmless)"
145
+ ],
146
+ "what_happened": "None of these were operator defects.",
147
+ "agent_response": "Corrected in seconds or worked around.",
148
+ "estimated_charged_time_lost_seconds": 0,
149
+ "work_lost": "None",
150
+ "affects_published_results": false,
151
+ "notes": ""
152
+ }
153
+ ],
154
+ "environment_vs_spec": [
155
+ {
156
+ "promised": "1x H100 80GB (disclosed override of the task's 8 GPUs)",
157
+ "observed": "1 visible NVIDIA H100 80GB HBM3, driver 570.124.06, CUDA 12.8, cuda_ok; landlock-isolated single device (gpu-access.json, preflight-result.json; container 2 item_3 nvidia-smi)",
158
+ "evidence": "preflight-result.json, gpu-access.json, container 2 item_3, container 4 item_3",
159
+ "material": false
160
+ },
161
+ {
162
+ "promised": "22 CPUs (requested)",
163
+ "observed": "No cgroup CPU quota (cpu.max 'max 100000', nr_throttled 0), cpu_affinity_count 180; agent measured 8-11 cores in use",
164
+ "evidence": "preflight-result.json; container 2 item_1516, item_1930, item_2070, item_2318",
165
+ "material": false
166
+ },
167
+ {
168
+ "promised": "224 GiB RAM",
169
+ "observed": "cgroup memory.max 250,720,165,888 B (233.5 GiB); memory.current often at the cap but ~223 GiB of it page cache (anon 4-6 GiB); oom_kill 0 throughout; node had 2 TiB",
170
+ "evidence": "container 2 item_1516, item_1520, item_2318, item_3072/3073, item_5451; container 3 item_1364-1367",
171
+ "material": false
172
+ },
173
+ {
174
+ "promised": "task.toml storage 1 TiB; persisted research workspace",
175
+ "observed": "Local overlay 14 TB (9-13 TB free); Weka /run-state 440 TB at 95-99% full (25 TB -> 5.3 TB free over the run) but no ENOSPC; /tmp is container-local and wiped at every restart (the agent's 200 GB local corpus copy had to be rebuilt 6 times); agent reported 'substantial storage waits' reading LMDB from Weka",
176
+ "evidence": "container 1 item_11 (100% at Oct 23), container 2 item_473, item_1275, item_1993, item_2080, item_5450; container 4 item_56; container 9 item_44",
177
+ "material": false
178
+ },
179
+ {
180
+ "promised": "Dockerfile: pytorch 2.4.0/cu12.1, Python 3.11, Uni-Core ace6fae (installed), Uni-Mol 90f52c4 at /opt/Uni-Mol, rdkit/lmdb/pandas/sklearn/numba",
181
+ "observed": "Python 3.11 at /opt/conda, unicore-0.0.1 egg installed, /opt/Uni-Mol/unimol2 present, unicore-train usable; matplotlib absent (not promised)",
182
+ "evidence": "container 9 item_58; container 1 item_9-item_13; container 2 item_146",
183
+ "material": false
184
+ },
185
+ {
186
+ "promised": "no network; development data read-only; evaluation roles absent",
187
+ "observed": "network_blocked/ipv4/ipv6 blocked, unix_ipc_ok; /workspace/data -> /task-data read-only (pretrain + downstream); evaluation_roles_absent true",
188
+ "evidence": "preflight-result.json; container 2 item_1995",
189
+ "material": false
190
+ },
191
+ {
192
+ "promised": "task.toml: 'the agent is not told' its 48 h budget; recovery notice should state true remaining seconds",
193
+ "observed": "Agent was told '172715 research seconds remain' once correctly (Oct 24 20:30Z) and six more times incorrectly at each restart (true remaining 102,980 .. 6,650 s)",
194
+ "evidence": "see incident 3",
195
+ "material": true
196
+ }
197
+ ],
198
+ "budget_awareness": "Correct at first: from the Oct 24 notice the agent derived the real deadline (NOTES.md:1712 at 2026-10-25T12:14Z 'fits remaining ~32h' - true remaining 32.2 h; container 2 item_4827 '11 hours ... fits within the remaining research time', item_5496 'nine hours ... within the remaining budget'). Contradicted by us afterwards: at every unplanned restart the runner re-sent '172715 research seconds remain at recovery', and the agent recorded it as fact (STATUS.md header at 16:03Z Oct 25: 'User reported172715 research seconds remaining at latest operator recovery15:54UTC', true ~102,980 s; recovery_20261026_1912/infrastructure_interruption.json at 19:13Z Oct 26: research_seconds_remaining_as_reported 172715, true ~6,590 s). No remaining-time statement appears after the first restart; CURRENT.md at 20:55Z plans multi-hour work with 8 min left. The run ended at exactly 172,800 charged seconds (research-state.json, status.json) with the submission intact (last_hash 4fdb6e62... == snapshot 103193 == restored /run-state/submission); research-state.error is null after the entrypoint correction.",
199
+ "total_estimated_operator_caused_loss_seconds": 7900,
200
+ "verdict": "minor (disclose)",
201
+ "verdict_reasoning": "The environment met or exceeded every promise (1 H100 visible, no CPU quota vs 22 promised, 233 GiB cgroup vs 224 promised, zero OOM kills, no ENOSPC, image matches the Dockerfile). The real operator/infrastructure problems were: six unplanned container restarts in 48 h (lines 10838/17809/18736/20130/21865/22851) that each killed the agent's GPU run, its fine-tunes and its local corpus copy, costing roughly 2 h of charged time (~4.5% of budget) in re-copying, re-verifying and re-running ~9k updates plus ~10 fine-tunes; a runner bug that re-sent the one-time pause notice with '172715 research seconds remain' at all six restarts, which the agent demonstrably believed (its own records at 16:03Z Oct 25 and 19:13Z Oct 26), so its final hours were planned on a 48 h horizon it did not have; one 30 s capacity retry that also killed its production trainer 12 min before the end; and a post-budget infer.sh/encoder.json check bug that was corrected without touching research time. None of this altered the published package: the final submission is the 103,193 s snapshot published at 01:11Z Oct 26, before five of the six restarts, and every later candidate was rejected by the agent's own full 24-task reviews. The losses are real but bounded and did not cost a publication, so this is a disclose-level case rather than grounds for a rerun.",
202
+ "recommended_remedy": "disclose (and fix runtime.py so recovery-notice.txt is consumed after first use and any re-delivered notice states the true remaining seconds)",
203
+ "open_questions": [
204
+ "Why did the Beaker job die six times between Oct 25 15:52Z and Oct 26 18:56Z (preemption of an 'urgent' job, node failures, or something in the runtime)? The run root has no per-job records for experiment 01M5QSJCAZ9GTSK9FCVP7WQ65A except the last job in completion-correction/receipt.json; Beaker job history is needed.",
205
+ "Was the 2026-10-25T22:11Z SIGTERM to the trainer in Codex exec session 84190 caused by Codex exec-session reaping (harness) or something else? Same mechanism may explain why the capacity-retry Codex restart killed session 18591.",
206
+ "Is 'substantial storage waits' on the Weka LMDB mount (which drove the agent to keep a 200 GB local copy that every restart destroyed) considered part of the intended environment? The data mount is on a filesystem that was 95-99% full for the whole run.",
207
+ "Should the agent be told remaining seconds at all (task.toml says no), and if so should other runs' restart prompts be checked for the same stale-notice bug (any run with a recovery-notice.txt and attempt > the recovery that created it)?"
208
+ ]
209
+ }
reviews/fairness-20261031/per-task/probabilistic-global-weather.json ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task": "probabilistic-global-weather",
3
+ "run_root": "/weka/oe-adapt-default/stevenc/science-speedrun-runs/probabilistic-global-weather-astra-xhigh-1h100-48h-20261024f",
4
+ "containers": 14,
5
+ "containers_note": "3 Beaker experiments (01M5QY04 preempted -> 01M5TFR6 auto-resumed 11 times within the same experiment -> 01M5ZQRX final 899 s) = 14 runtime.py invocations (research-state attempt=14, attempts/001-013 preflight archives). Every one of the 14 Codex turns ended by container death or budget end: trajectory.jsonl has 14 thread.started, 14 turn.started, 1 turn.failed (capacity) and ZERO turn.completed events.",
6
+ "turns": 14,
7
+ "charged_seconds": 172800,
8
+ "research_state_error": null,
9
+ "timeline_utc": [
10
+ "A/attempt1 T1 2026-10-24 21:46:49 -> 10-25 ~15:20 hard-killed (status.json phase=running, elapsed 63163; recoveries/preemption-01M5QY04*/recovery.json). Uncharged gap 6.5 h; new experiment created 21:34, container up ~21:51.",
11
+ "B/attempt2 T2 21:51 -> 10-26 00:33 died; attempt3 T3 00:38 -> ~03:48 died; attempt4 T4 03:53 -> 06:37 died; attempt5 T5 06:43 -> 10:39 died; attempt6 T6 10:44 -> 14:31 died; attempt7 T7 14:57 -> 16:57 turn.failed 'model at capacity' (capacity-retries.jsonl, 30 s) + T8 16:57 -> 17:08 died; attempt8 T9 17:27 -> 19:29 died; UNCHARGED GAP 5.4 h; attempt9 T10 10-27 00:51 -> 02:58 died; attempt10 T11 03:12 -> 05:11 died; attempt11 T12 05:50 -> ~08:40 died; attempt12 T13 08:59 -> 11:51 died; attempt13 preflight 11:54 FAILED 'Insufficient research storage' (attempts/013/preflight.jsonl) -> job failed; uncharged gap 12 h.",
12
+ "C/attempt14 T14 2026-10-27 23:48:47 -> 10-28 00:03:25 (898.8 s remaining per recoveries/storage-preflight-20261027a/recovery.json); elapsed reached 172800; submission restored from snapshot 169524 (publication-storage.json, sha 8381ac7e... == research-state.last_hash)."
13
+ ],
14
+ "incidents": [
15
+ {
16
+ "kind": "4 infrastructure interruptions (repeated container deaths)",
17
+ "ownership": "infrastructure",
18
+ "when_charged_seconds": "63178 (first death) then roughly every 7,000-14,000 charged s: ~72.8k, ~84k, ~94k, ~108k, ~121k, ~129k, ~136k, ~144k, ~151k, ~161k, ~171.9k",
19
+ "evidence": [
20
+ "trajectory.jsonl lines 4726,5340,6009,6365,7444,8397,8992,9502,10123,10828,11831,12877 (thread.started, no preceding turn.completed)",
21
+ "T2 item_9, T3 item_6, T4 item_10 (nvidia-smi 0%/1MiB item_3), T5 item_9, T6 item_6, T7 item_25, T9 item_3, T10 item_16, T11 item_6, T12 item_5, T13 item_4, T14 item_6 (agent finds all training/eval processes gone each time)",
22
+ "T8 item_2 ps: docker-init etime 02:01:22; T10 item_4 ps: weather_broker.py etime 00:29 (fresh containers)",
23
+ "attempts/001..013 preflight archive mtimes; recoveries/preemption-01M5QY04Y8D8XQ5XRBGPCJ7FH3/recovery.json; workspace/research/experiment-00{2,3,6,7}/interruption-00{1,2,3}; RESEARCH.md lines 315-325, 377-381, 423-427, 477-481, 685-687, 806-812, 880-884, 938-948, 1046-1052, 1146-1148"
24
+ ],
25
+ "what_happened": "Twelve times the research container was hard-killed mid-turn (Beaker job priority urgent, minRuntime 2h, autoResume true; operator labeled the first one 'preemption'); median lifetime of attempts 2-12 was ~2.8 h. Each death killed the single-GPU WN2 training worker (or the development evaluation) the agent had running, and Codex was resumed with the plain CONTINUE prompt (no recovery-notice.txt exists).",
26
+ "agent_response": "Model-side mitigation was exemplary: strict checkpoint/Adam restoration under its original deadline, archived interruption records, history reconciliation, bitwise continuity audits, recovery launchers (recover_experiment_007_interruption_00{1,2,3}.py, retry_*.py, observe_completed_stage_reconciliation*.py). Typical time from container start to GPU training running again: 18 s (T9), 1.5 min (T12, T13), 3-6 min (T3, T4, T10), 10 min (T11, after two launcher mistakes), 4 min (T2, T7).",
27
+ "estimated_charged_time_lost_seconds": 16500,
28
+ "work_lost": "Partial updates/compiles lost at each kill (coarse 32/64 and 24/64 microbatches; native 48/64 ~300 s; AR2 48/64 ~670 s; AR2 compilation; AR7 first batch; AR8 first update ~20-30 min) ~3,000 s; checkpoint reload + XLA recompile/autotune + cold input reads after each restart (restarted updates 248 s vs 52 s, 1164 s vs 890 s, 3126 s) ~5,000 s; agent recovery/re-verification work ~4,500 s; two development evaluations interrupted (003: July forecast lost, July+October re-run, T5 items 9-28; 005: October lost and re-run, T6 items 6-33) ~4,000 s; 12x10 s heartbeat penalties. Bigger uncharged harm: the 6.5 h and 5.4 h outages consumed the agent's per-run 24 h training cap (starter README says interruptions count), so curricula were cut 456->428 updates (T2 items 22/35/38; RESEARCH.md 315-325) and 441->436 updates (analysis/experiment-006-third-interruption-budget-review.json: remaining 10.1 h vs 13.15 h needed).",
29
+ "affects_published_results": true,
30
+ "notes": "Charging itself was correct: the ~26 h of downtime between containers was not charged (sum of per-turn wall times ~= 172.8k s). The harm is lost GPU work, forced curriculum reductions and roughly 4.5 charged hours of recovery engineering on a task whose core artifact is a 20-24 h single-GPU training run."
31
+ },
32
+ {
33
+ "kind": "3 resource shortfall / 2 mount defect (shared research storage exhausted)",
34
+ "ownership": "operator",
35
+ "when_charged_seconds": 171901,
36
+ "evidence": [
37
+ "attempts/013/preflight.jsonl: AssertionError: Insufficient research storage",
38
+ "recoveries/storage-preflight-20261027a/{recovery.json,status.json}",
39
+ "attempts/*/preflight-result.json research_storage_free_bytes: 26.8 TB (10-24) -> 5.4 TB (10-26 20:11) -> 2.25 TB (22:47) -> 2.76 TB (10-27 01:55) -> <2 TiB at 11:54",
40
+ "T1 item_151 df: weka /run-state 440T size, 416T used, 25T avail (95%) at trial start"
41
+ ],
42
+ "what_happened": "The shared Weka volume hosting /workspace/research filled up (other jobs, incl. 9 sibling native-eval runs of this task) until the per-attempt storage probe (task_profiles storage_gib=2048) failed, which turned attempt 12's container death into a job failure; the operator relaunched 10.6 h later with 899 s left.",
43
+ "agent_response": "None possible (preflight happens before Codex). In the final 899 s the agent found its 56-member evaluation and rank diagnostic dead and relaunched them (T14 items 6-58); nothing could complete.",
44
+ "estimated_charged_time_lost_seconds": 900,
45
+ "work_lost": "In-flight 56-member streaming development evaluation of candidate 008 (second lead window) and the 6478/6560-panel rank diagnostic; the final 899 s were effectively useless.",
46
+ "affects_published_results": false,
47
+ "notes": "Submission 008 (published 11:11:51 UTC, 39 min before the death) survived intact (snapshot 169524 sha 8381ac7e... == final)."
48
+ },
49
+ {
50
+ "kind": "1 environment/image defect (root-owned git checkouts fail Git safe.directory for uid 1000)",
51
+ "ownership": "operator",
52
+ "when_charged_seconds": 80,
53
+ "evidence": [
54
+ "T1 item_19 (first training launch failed: CalledProcessError git rev-parse HEAD), item_21 ('fatal: detected dubious ownership in repository at /opt/weathernext'), item_22-24 (patch + resume ~21:50), item_31 (GIT_CONFIG env for /opt/weatherbenchX)",
55
+ "T6 item_224/227/229; T12 item_190/197; T14 item_37/48 (recurrence on /opt/weatherbenchX in CPU screens)",
56
+ "RESEARCH.md line 30, 769"
57
+ ],
58
+ "what_happened": "The image builds /opt/weathernext and /opt/weatherbenchX as root while the agent runs as uid 1000; the starter's train_stage.py and the evaluator's verify_metric_source() call `git rev-parse HEAD`, which fails with 'dubious ownership'. The very first training launch died on it and three later CPU diagnostics failed the same way.",
59
+ "agent_response": "Patched its copy of train_stage.py to pass `git -c safe.directory=...` and used GIT_CONFIG_* env vars; re-fixed in later scripts.",
60
+ "estimated_charged_time_lost_seconds": 600,
61
+ "work_lost": "None (restarted before any parameter update).",
62
+ "affects_published_results": false,
63
+ "notes": "Recurred because each fresh script had to carry the workaround; ~2-3 min each."
64
+ },
65
+ {
66
+ "kind": "2 mount defect (XLA per-fusion autotune cache / cross-directory rename unsupported on the Weka research mount)",
67
+ "ownership": "operator",
68
+ "when_charged_seconds": 620,
69
+ "evidence": [
70
+ "T1 item_72/item_77: XlaRuntimeError UNIMPLEMENTED ...jax-cache/xla_gpu_per_fusion_autotune_cache_dir/tmp/...; Invalid cross-device link (first gradient compile at ~21:57 after 411 s setup)",
71
+ "T1 item_74/75 (fix: JAX_PERSISTENT_CACHE_ENABLE_XLA_CACHES='' ; training resumed ~21:59:30)",
72
+ "T11 item_53: OSError [Errno 18] Invalid cross-device link on rename within /workspace/research (agent's archival helper)",
73
+ "RESEARCH.md lines 34, 54, 165, 946"
74
+ ],
75
+ "what_happened": "XLA's optional per-fusion autotune cache writes a temp file and links/renames it; the research mount (Weka, reached via the /workspace/research -> /run-state symlink) returns EXDEV, killing the first training attempt at its first compile. The same semantics broke a cross-directory rename in the agent's own recovery helper later.",
76
+ "agent_response": "Disabled only the optional XLA per-fusion autotune cache; kept the JAX persistent compilation cache (which works: 'saved compiler artifacts helped the restart reach GPU execution quickly' T3 item_20; inference 219 s -> 47 s with bundled cache) and replaced it with explicit autotune.pb dumps; switched the helper to copy+unlink.",
77
+ "estimated_charged_time_lost_seconds": 800,
78
+ "work_lost": "~12 min in T1 (setup/compile redone); ~2 min in T11. Did NOT make compilation caching unusable; it only forced re-autotuning on cold compiles, which added a few minutes to each of the 10 post-restart recompiles (counted in incident 1).",
79
+ "affects_published_results": false,
80
+ "notes": "The starter's train.py already anticipates EXDEV on overlayfs; the task expects a POSIX research disk."
81
+ },
82
+ {
83
+ "kind": "1/5 environment vs task spec: user namespaces disabled; operator substituted a root-owned inference broker",
84
+ "ownership": "operator (disclosed adaptation)",
85
+ "when_charged_seconds": 330,
86
+ "evidence": [
87
+ "T1 item_32: bwrap: No permissions to create new namespace",
88
+ "T1 items 35-56 (agent's own Landlock fallback fails CUDA init), item_57-59 (discovers /opt/speedrun/weather_broker.py, broker probe passes)",
89
+ "weather-broker.log = 'WEATHER_BROKER_READY' only; operator/weather_broker.py, weather_bootstrap.py, weather_namespace_adapter.py; adaptation.json; execution-boundary.patch",
90
+ "T1 item_254-256 (broker stages package files 0444; agent's cache copy made writable)"
91
+ ],
92
+ "what_happened": "README/contract promise Bubblewrap namespace isolation for the development evaluator; the Beaker host forbids unprivileged user namespaces. weather_bootstrap.py starts weather_broker.py as root before runtime.py; it listens on /run/weather-inference/broker.sock, copies the submission + public inputs to a staging dir (read-only, 0444/0555), runs infer.sh as UID 10001 under a Landlock/seccomp boundary and copies outputs back; /opt/weathernext/wn2/namespace_inference.py is replaced by the adapter so verify_case/development.py call the broker. The log only prints the ready line; broker errors are returned to callers as JSON, none logged.",
93
+ "agent_response": "Spent ~7 min (21:52-21:59) discovering the namespace failure and the broker, then used it for all development inference; added a chmod to its infer.sh cache copy because staged files are read-only (~2 min, 23:21-23:23).",
94
+ "estimated_charged_time_lost_seconds": 540,
95
+ "work_lost": "None",
96
+ "affects_published_results": false,
97
+ "notes": "Disclosed in adaptation.json; no broker failures found. Extra staging copies add per-inference overhead (disclosed limitation)."
98
+ },
99
+ {
100
+ "kind": "6 API-side (capacity retry)",
101
+ "ownership": "operator",
102
+ "when_charged_seconds": 129000,
103
+ "evidence": [
104
+ "capacity-retries.jsonl (turn 7, 30 s, 2026-10-26 16:56:55 UTC)",
105
+ "trajectory.jsonl line 8896-8900 (turn.failed 'Selected model is at capacity')",
106
+ "codex.stderr: 1 model-refresh timeout, 4 'missing field cmd' arg parse errors, 3 apply_patch verification failures, 2 write_stdin unknown pid"
107
+ ],
108
+ "what_happened": "One capacity failure ended turn 7; runtime slept 30 s and re-prompted (turn 8).",
109
+ "agent_response": "Resumed monitoring immediately.",
110
+ "estimated_charged_time_lost_seconds": 90,
111
+ "work_lost": "None",
112
+ "affects_published_results": false,
113
+ "notes": "codex.stderr apply_patch/arg errors are model-side (malformed patches/args), corrected within seconds; 'use_legacy_landlock deprecated' error item at each thread start is benign."
114
+ },
115
+ {
116
+ "kind": "7 budget/timing: agent never told the 48 h budget or that restarts were occurring",
117
+ "ownership": "task-design + operator prompt",
118
+ "when_charged_seconds": null,
119
+ "evidence": [
120
+ "tasks/.../task.toml comment: 'the agent is not told'",
121
+ "runtime.py CONTINUE prompt text (no remaining-time info); no recovery-notice.txt in run root",
122
+ "T14 item_1 ('I'll use those results to guide the next experiment') with 899 s left",
123
+ "grepmsg for remaining/budget: agent only reasons about its own per-run 24 h deadlines"
124
+ ],
125
+ "what_happened": "By design the agent is not told the trial budget; the runner also gave no notice after any of the 12 restarts, so the agent had to infer each interruption from missing processes and could not plan the last 899 s.",
126
+ "agent_response": "Inferred restarts from process tables; kept a conservative per-run 24 h cap counting downtime.",
127
+ "estimated_charged_time_lost_seconds": 0,
128
+ "work_lost": "Last 899 s unusable",
129
+ "affects_published_results": false,
130
+ "notes": "Bookkeeping consistent: research-state/status/trial agree (172800 s, attempt 14, turns 14, error null); preemption recovery elapsed 63177.9 vs status 63163 (+heartbeat); storage recovery remaining 898.8 s."
131
+ }
132
+ ],
133
+ "environment_vs_spec": [
134
+ {
135
+ "promised": "1x H100 (disclosed override of 8)",
136
+ "observed": "NVIDIA H100 80GB HBM3, 1 visible, CUDA 12.8, driver 570.124.06",
137
+ "evidence": "T1 item_2 nvidia-smi; preflight-result.json; gpu-access.json",
138
+ "material": false
139
+ },
140
+ {
141
+ "promised": "22 CPUs",
142
+ "observed": "sched affinity 180 CPUs visible (cpu_affinity_count 180); agent voluntarily pinned to cores 3-24",
143
+ "evidence": "preflight-result.json; T2 item_26 taskset; RESEARCH.md line 15",
144
+ "material": false
145
+ },
146
+ {
147
+ "promised": "224 GiB RAM, 32 GiB shm",
148
+ "observed": "cgroup memory.max 250,720,149,504 B (233.5 GiB); memory.events max>0 from page-cache reclaim, oom/oom_kill 0 throughout; worker HWM 152 GiB",
149
+ "evidence": "T2 item_26; T1 item_151; RESEARCH.md 225, 791, 799",
150
+ "material": false
151
+ },
152
+ {
153
+ "promised": "2 TiB research storage (task.toml storage_mb) on a writable POSIX disk",
154
+ "observed": "research dir is a symlink into a 440 TB shared Weka mount that was 95% full at start and dropped below 2 TiB free on 10-27 11:54 (preflight assertion failed); EXDEV on XLA autotune-cache link and on cross-directory rename",
155
+ "evidence": "T1 item_151 df; attempts/*/preflight-result.json; attempts/013/preflight.jsonl; T1 item_72; T11 item_53",
156
+ "material": true
157
+ },
158
+ {
159
+ "promised": "Bubblewrap namespace isolation for development evaluation (README/contract)",
160
+ "observed": "unprivileged user namespaces disabled; operator broker (UID 10001 + Landlock + seccomp) substituted and disclosed",
161
+ "evidence": "T1 item_32; adaptation.json; operator/weather_broker.py",
162
+ "material": false
163
+ },
164
+ {
165
+ "promised": "starter train.py/evaluate.py run as-is (git rev-parse of pinned repos)",
166
+ "observed": "/opt/weathernext and /opt/weatherbenchX root-owned -> Git 'dubious ownership' for uid 1000",
167
+ "evidence": "T1 item_21; T6 item_224; T12 item_190",
168
+ "material": true
169
+ },
170
+ {
171
+ "promised": "no network",
172
+ "observed": "IPv4/IPv6 blocked (EPERM), AF_UNIX ok",
173
+ "evidence": "preflight-result.json",
174
+ "material": false
175
+ },
176
+ {
177
+ "promised": "uninterrupted 48 h container (implicit)",
178
+ "observed": "12 container deaths in 48 charged hours; 74.3 h wall; ~26 h uncharged downtime",
179
+ "evidence": "see incident 1",
180
+ "material": true
181
+ }
182
+ ],
183
+ "budget_awareness": "The agent was never told the 48 h budget (task design) nor given any restart notice (no recovery-notice.txt; CONTINUE prompt only), and it never mentions the trial budget; it only tracked its own per-training-run 24 h caps (e.g., T3 item_63 '8.4 hours left before the original deadline', T12 item_24 'about 12 minutes before the original deadline'). It entered the final 899 s container believing it had time for the next experiment (T14 item_1). Operator bookkeeping is internally consistent: research-state.json, status.json and trial.json agree (elapsed 172800, attempt 14, turns 14, error null); recoveries record 63177.9 s at the preemption and 898.8 s remaining at the storage recovery; final submission sha 8381ac7e... equals the last snapshot (169524 s) and the publication-storage.json restore.",
184
+ "total_estimated_operator_caused_loss_seconds": 19400,
185
+ "verdict": "material (unfair)",
186
+ "verdict_reasoning": "The run's core activity is a ~20-24 h single-H100 WN2 training curriculum, yet the container was hard-killed 12 times in 48 charged hours (attempt lifetimes mostly 2-4 h; the trajectory contains no turn.completed at all), each time killing the GPU worker or the development evaluation. Beyond roughly 4.5-5.4 charged hours spent on partial-update loss, recompilation, re-verification and re-running interrupted evaluations (~19,000 s, ~11% of budget), the two long uncharged outages (6.5 h and 5.4 h) ate into the task's 24 h per-run training cap and forced the agent to cut its curricula from 456 to 428 and from 441 to 436 updates, so the published model trained less than the model intended. The shared Weka volume then filled below the 2 TiB probe threshold, which converted the twelfth death into a job failure and left only an unusable 899 s final turn. The image defects (root-owned git checkouts; EXDEV on the research mount) cost ~25 min and were worked around cleanly. The agent's own mistakes (two bad relaunch commands in T11, malformed patches) were minor and corrected in minutes; its checkpoint/recovery discipline kept the submission (008, 4-date dev reward 0.7014 vs 005 0.6969) valid, so the result stands but is a lower bound on what this model could do on a stable allocation.",
187
+ "recommended_remedy": "full rerun on a non-preemptible allocation with the research mount on a disk that supports rename/link semantics and has guaranteed free space; at minimum disclose the 12 interruptions and the curriculum reductions alongside the score",
188
+ "open_questions": [
189
+ "Root cause of the 12 container deaths inside Beaker experiment 01M5TFR6870BT2VYWJ2D0HZCVS (preemption after minRuntime 2h vs node failures): no launch.log/Beaker event log is archived in the run root; only the first death is labeled 'preemption' by the operator.",
190
+ "Should operator downtime count against the task's 24 h per-training-run cap? The agent applied the starter README literally ('interruptions count'), which is why the outages translated into fewer training updates.",
191
+ "Run suffix 'f': no sibling directories *-20261024a..e exist; the operator's adapted-boundary validation on 10-24 (adapted-boundary-validation-20261024a/probabilistic-global-weather/boundary.log.attempt1-5, attempt1 ModuleNotFoundError adapted_boundary) went through five pre-clock iterations, consistent with a-e being uncharged validation launches rather than abandoned research trials, but this could not be confirmed from the filesystem.",
192
+ "What consumed the shared Weka volume between 10-26 20:11 (5.4 TB free) and 10-27 11:54 (<2 TiB): likely the parallel native-eval jobs for this task; the agent's own research directory size was not measured."
193
+ ]
194
+ }
shared/package-files/d6/d60192201c9d72dc0ecb4b9d51754632551ca3d1060a60f9a710950111511895/h19-us ADDED
Binary file (633 Bytes). View file
 
shared/package-files/d6/d60192201c9d72dc0ecb4b9d51754632551ca3d1060a60f9a710950111511895/h19us ADDED
Binary file (633 Bytes). View file
 
shared/package-files/d6/d60204d1c6facf9b83b6964a8df47e10b723d271615721353a942ac835a8d33a/wy520-24 ADDED
Binary file (1.69 kB). View file
 
shared/package-files/d6/d60204d1c6facf9b83b6964a8df47e10b723d271615721353a942ac835a8d33a/wyse520-24 ADDED
Binary file (1.69 kB). View file
 
shared/package-files/d6/d6073d10c880d7f39c13f6c77d6418f6bc372adae5027eae6139c1680f28a6c9/basic4 ADDED
Binary file (857 Bytes). View file
 
shared/package-files/d6/d6073d10c880d7f39c13f6c77d6418f6bc372adae5027eae6139c1680f28a6c9/mai ADDED
Binary file (857 Bytes). View file
 
shared/package-files/d6/d60e39a1cd75e59651dc27cc5b56c23ec785e404f3e177fa221dba351ab28dfb/decomp_cholesky.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.linalg` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
10
+ 'cho_solve_banded', 'LinAlgError', 'get_lapack_funcs'
11
+ ]
12
+
13
+
14
+ def __dir__():
15
+ return __all__
16
+
17
+
18
+ def __getattr__(name):
19
+ return _sub_module_deprecation(sub_package="linalg", module="decomp_cholesky",
20
+ private_modules=["_decomp_cholesky"], all=__all__,
21
+ attribute=name)
shared/package-files/d6/d611a87944137b0e68d039c28cb579fa139f12e4a8206397181caae4aa403fb0/test_deprecate.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from textwrap import dedent
2
+
3
+ import pytest
4
+
5
+ from pandas.util._decorators import deprecate
6
+
7
+ import pandas._testing as tm
8
+
9
+
10
+ def new_func():
11
+ """
12
+ This is the summary. The deprecate directive goes next.
13
+
14
+ This is the extended summary. The deprecate directive goes before this.
15
+ """
16
+ return "new_func called"
17
+
18
+
19
+ def new_func_no_docstring():
20
+ return "new_func_no_docstring called"
21
+
22
+
23
+ def new_func_wrong_docstring():
24
+ """Summary should be in the next line."""
25
+ return "new_func_wrong_docstring called"
26
+
27
+
28
+ def new_func_with_deprecation():
29
+ """
30
+ This is the summary. The deprecate directive goes next.
31
+
32
+ .. deprecated:: 1.0
33
+ Use new_func instead.
34
+
35
+ This is the extended summary. The deprecate directive goes before this.
36
+ """
37
+
38
+
39
+ def test_deprecate_ok():
40
+ depr_func = deprecate("depr_func", new_func, "1.0", msg="Use new_func instead.")
41
+
42
+ with tm.assert_produces_warning(FutureWarning):
43
+ result = depr_func()
44
+
45
+ assert result == "new_func called"
46
+ assert depr_func.__doc__ == dedent(new_func_with_deprecation.__doc__)
47
+
48
+
49
+ def test_deprecate_no_docstring():
50
+ depr_func = deprecate(
51
+ "depr_func", new_func_no_docstring, "1.0", msg="Use new_func instead."
52
+ )
53
+ with tm.assert_produces_warning(FutureWarning):
54
+ result = depr_func()
55
+ assert result == "new_func_no_docstring called"
56
+
57
+
58
+ def test_deprecate_wrong_docstring():
59
+ msg = "deprecate needs a correctly formatted docstring"
60
+ with pytest.raises(AssertionError, match=msg):
61
+ deprecate(
62
+ "depr_func", new_func_wrong_docstring, "1.0", msg="Use new_func instead."
63
+ )
shared/package-files/d6/d617f6bdf5c9ff46889dc63e6d9320c794d74f3188e3d6027d5c42858aec2e7a/test_bisect_k_means.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from sklearn.cluster import BisectingKMeans
5
+ from sklearn.metrics import v_measure_score
6
+ from sklearn.utils._testing import assert_allclose, assert_array_equal
7
+ from sklearn.utils.fixes import CSR_CONTAINERS
8
+
9
+
10
+ @pytest.mark.parametrize("bisecting_strategy", ["biggest_inertia", "largest_cluster"])
11
+ @pytest.mark.parametrize("init", ["k-means++", "random"])
12
+ def test_three_clusters(bisecting_strategy, init):
13
+ """Tries to perform bisect k-means for three clusters to check
14
+ if splitting data is performed correctly.
15
+ """
16
+ X = np.array(
17
+ [[1, 1], [10, 1], [3, 1], [10, 0], [2, 1], [10, 2], [10, 8], [10, 9], [10, 10]]
18
+ )
19
+ bisect_means = BisectingKMeans(
20
+ n_clusters=3,
21
+ random_state=0,
22
+ bisecting_strategy=bisecting_strategy,
23
+ init=init,
24
+ )
25
+ bisect_means.fit(X)
26
+
27
+ expected_centers = [[2, 1], [10, 1], [10, 9]]
28
+ expected_labels = [0, 1, 0, 1, 0, 1, 2, 2, 2]
29
+
30
+ assert_allclose(
31
+ sorted(expected_centers), sorted(bisect_means.cluster_centers_.tolist())
32
+ )
33
+ assert_allclose(v_measure_score(expected_labels, bisect_means.labels_), 1.0)
34
+
35
+
36
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
37
+ def test_sparse(csr_container):
38
+ """Test Bisecting K-Means with sparse data.
39
+
40
+ Checks if labels and centers are the same between dense and sparse.
41
+ """
42
+
43
+ rng = np.random.RandomState(0)
44
+
45
+ X = rng.rand(20, 2)
46
+ X[X < 0.8] = 0
47
+ X_csr = csr_container(X)
48
+
49
+ bisect_means = BisectingKMeans(n_clusters=3, random_state=0)
50
+
51
+ bisect_means.fit(X_csr)
52
+ sparse_centers = bisect_means.cluster_centers_
53
+
54
+ bisect_means.fit(X)
55
+ normal_centers = bisect_means.cluster_centers_
56
+
57
+ # Check if results is the same for dense and sparse data
58
+ assert_allclose(normal_centers, sparse_centers, atol=1e-8)
59
+
60
+
61
+ @pytest.mark.parametrize("n_clusters", [4, 5])
62
+ def test_n_clusters(n_clusters):
63
+ """Test if resulting labels are in range [0, n_clusters - 1]."""
64
+
65
+ rng = np.random.RandomState(0)
66
+ X = rng.rand(10, 2)
67
+
68
+ bisect_means = BisectingKMeans(n_clusters=n_clusters, random_state=0)
69
+ bisect_means.fit(X)
70
+
71
+ assert_array_equal(np.unique(bisect_means.labels_), np.arange(n_clusters))
72
+
73
+
74
+ def test_one_cluster():
75
+ """Test single cluster."""
76
+
77
+ X = np.array([[1, 2], [10, 2], [10, 8]])
78
+
79
+ bisect_means = BisectingKMeans(n_clusters=1, random_state=0).fit(X)
80
+
81
+ # All labels from fit or predict should be equal 0
82
+ assert all(bisect_means.labels_ == 0)
83
+ assert all(bisect_means.predict(X) == 0)
84
+
85
+ assert_allclose(bisect_means.cluster_centers_, X.mean(axis=0).reshape(1, -1))
86
+
87
+
88
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS + [None])
89
+ def test_fit_predict(csr_container):
90
+ """Check if labels from fit(X) method are same as from fit(X).predict(X)."""
91
+ rng = np.random.RandomState(0)
92
+
93
+ X = rng.rand(10, 2)
94
+
95
+ if csr_container is not None:
96
+ X[X < 0.8] = 0
97
+ X = csr_container(X)
98
+
99
+ bisect_means = BisectingKMeans(n_clusters=3, random_state=0)
100
+ bisect_means.fit(X)
101
+
102
+ assert_array_equal(bisect_means.labels_, bisect_means.predict(X))
103
+
104
+
105
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS + [None])
106
+ def test_dtype_preserved(csr_container, global_dtype):
107
+ """Check that centers dtype is the same as input data dtype."""
108
+ rng = np.random.RandomState(0)
109
+ X = rng.rand(10, 2).astype(global_dtype, copy=False)
110
+
111
+ if csr_container is not None:
112
+ X[X < 0.8] = 0
113
+ X = csr_container(X)
114
+
115
+ km = BisectingKMeans(n_clusters=3, random_state=0)
116
+ km.fit(X)
117
+
118
+ assert km.cluster_centers_.dtype == global_dtype
119
+
120
+
121
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS + [None])
122
+ def test_float32_float64_equivalence(csr_container):
123
+ """Check that the results are the same between float32 and float64."""
124
+ rng = np.random.RandomState(0)
125
+ X = rng.rand(10, 2)
126
+
127
+ if csr_container is not None:
128
+ X[X < 0.8] = 0
129
+ X = csr_container(X)
130
+
131
+ km64 = BisectingKMeans(n_clusters=3, random_state=0).fit(X)
132
+ km32 = BisectingKMeans(n_clusters=3, random_state=0).fit(X.astype(np.float32))
133
+
134
+ assert_allclose(km32.cluster_centers_, km64.cluster_centers_)
135
+ assert_array_equal(km32.labels_, km64.labels_)
136
+
137
+
138
+ @pytest.mark.parametrize("algorithm", ("lloyd", "elkan"))
139
+ def test_no_crash_on_empty_bisections(algorithm):
140
+ # Non-regression test for:
141
+ # https://github.com/scikit-learn/scikit-learn/issues/27081
142
+ rng = np.random.RandomState(0)
143
+ X_train = rng.rand(3000, 10)
144
+ bkm = BisectingKMeans(n_clusters=10, algorithm=algorithm).fit(X_train)
145
+
146
+ # predict on scaled data to trigger pathologic case
147
+ # where the inner mask leads to empty bisections.
148
+ X_test = 50 * rng.rand(100, 10)
149
+ labels = bkm.predict(X_test) # should not crash with idiv by 0
150
+ assert np.isin(np.unique(labels), np.arange(10)).all()
151
+
152
+
153
+ def test_one_feature():
154
+ # Check that no error is raised when there is only one feature
155
+ # Non-regression test for:
156
+ # https://github.com/scikit-learn/scikit-learn/issues/27236
157
+ X = np.random.normal(size=(128, 1))
158
+ BisectingKMeans(bisecting_strategy="biggest_inertia", random_state=0).fit(X)
shared/package-files/d6/d61a25ad2b1d631a7512ca1adb27d11cb8e26250918b78d8672db25a6eb66155/alias.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from distutils.errors import DistutilsOptionError
2
+
3
+ from setuptools.command.setopt import edit_config, option_base, config_file
4
+
5
+
6
+ def shquote(arg):
7
+ """Quote an argument for later parsing by shlex.split()"""
8
+ for c in '"', "'", "\\", "#":
9
+ if c in arg:
10
+ return repr(arg)
11
+ if arg.split() != [arg]:
12
+ return repr(arg)
13
+ return arg
14
+
15
+
16
+ class alias(option_base):
17
+ """Define a shortcut that invokes one or more commands"""
18
+
19
+ description = "define a shortcut to invoke one or more commands"
20
+ command_consumes_arguments = True
21
+
22
+ user_options = [
23
+ ('remove', 'r', 'remove (unset) the alias'),
24
+ ] + option_base.user_options
25
+
26
+ boolean_options = option_base.boolean_options + ['remove']
27
+
28
+ def initialize_options(self):
29
+ option_base.initialize_options(self)
30
+ self.args = None
31
+ self.remove = None
32
+
33
+ def finalize_options(self):
34
+ option_base.finalize_options(self)
35
+ if self.remove and len(self.args) != 1:
36
+ raise DistutilsOptionError(
37
+ "Must specify exactly one argument (the alias name) when "
38
+ "using --remove"
39
+ )
40
+
41
+ def run(self):
42
+ aliases = self.distribution.get_option_dict('aliases')
43
+
44
+ if not self.args:
45
+ print("Command Aliases")
46
+ print("---------------")
47
+ for alias in aliases:
48
+ print("setup.py alias", format_alias(alias, aliases))
49
+ return
50
+
51
+ elif len(self.args) == 1:
52
+ (alias,) = self.args
53
+ if self.remove:
54
+ command = None
55
+ elif alias in aliases:
56
+ print("setup.py alias", format_alias(alias, aliases))
57
+ return
58
+ else:
59
+ print("No alias definition found for %r" % alias)
60
+ return
61
+ else:
62
+ alias = self.args[0]
63
+ command = ' '.join(map(shquote, self.args[1:]))
64
+
65
+ edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)
66
+
67
+
68
+ def format_alias(name, aliases):
69
+ source, command = aliases[name]
70
+ if source == config_file('global'):
71
+ source = '--global-config '
72
+ elif source == config_file('user'):
73
+ source = '--user-config '
74
+ elif source == config_file('local'):
75
+ source = ''
76
+ else:
77
+ source = '--filename=%r' % source
78
+ return source + name + ' ' + command
shared/package-files/d6/d61cbc9dfcc6668ecbad20a8bfd94b72662f2caf744c8f6e85e11c1749207480/CUDAGeneratorImpl.h ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Generator.h>
4
+ #include <ATen/cuda/PhiloxCudaState.h>
5
+ #include <ATen/Context.h>
6
+ #include <limits>
7
+ #include <atomic>
8
+
9
+ namespace at {
10
+ /**
11
+ * Note [CUDA Graph-safe RNG states]
12
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13
+ *
14
+ * Strategy:
15
+ * ~~~~~~~~~
16
+ * (It helps to look at
17
+ * cuda/detail/PhiloxCudaStateRaw.cuh and
18
+ * cuda/detail/UnpackRaw.cuh
19
+ * while you read this.)
20
+ *
21
+ * A CUDA graph containing multiple RNG ops behaves like a
22
+ * single giant kernel from the perspective of ops external
23
+ * to the graph. During graph capture, logic in CUDAGeneratorImpl
24
+ * records the total of all offset increments that occur in the
25
+ * graphed region, and records the final total as the offset for
26
+ * the entire graph.
27
+ *
28
+ * When the graph reruns, the logic that reruns it
29
+ * increments this device's CUDA generator's offset
30
+ * by that total.
31
+ *
32
+ * Meanwhile, within the graph, at capture time, instead of
33
+ * populating PhiloxCudaStates with the uint64_t offset pulled
34
+ * directly from the global state, PhiloxCudaState uses a pointer
35
+ * to a one-element stream-local int64_t device tensor
36
+ * holding an initial offset value, and a uint64_t holding an
37
+ * intra-graph offset. (The intra-graph offset starts from zero
38
+ * when capture begins.) In each consumer kernel,
39
+ * at::cuda::philox::unpack computes the offset to use for this kernel
40
+ * as intra-graph offset + *initial offset.
41
+ *
42
+ * When the graph reruns, the logic that reruns it first
43
+ * fill_s the initial offset tensor with this device's
44
+ * CUDA generator's current offset.
45
+ *
46
+ * The control flow above ensures graphed execution is bitwise
47
+ * identical to eager execution as long as RNG ops are enqueued
48
+ * from a single thread, even if RNG ops and graphs containing
49
+ * RNG ops are enqueued and run simultaneously on multiple streams.
50
+ *
51
+ * Usage:
52
+ * ~~~~~~
53
+ * PhiloxCudaState in this file, and unpack() in
54
+ * cuda/CUDAGraphsUtils.cuh allow non-divergent use of
55
+ * CUDAGeneratorImpl whether graph capture is underway or not.
56
+ *
57
+ * Each PhiloxCudaState instance should be used for one and only one
58
+ * consumer kernel.
59
+ *
60
+ * Example (see e.g. native/cuda/Dropout.cu):
61
+ *
62
+ * #include <ATen/cuda/CUDAGeneratorImpl.h>
63
+ * #include <ATen/cuda/CUDAGraphsUtils.cuh>
64
+ *
65
+ * __global__ void kernel(..., PhiloxCudaState philox_args) {
66
+ * auto seeds = at::cuda::philox::unpack(philox_args);
67
+ * IndexType idx = blockIdx.x * blockDim.x + threadIdx.x;
68
+ * curandStatePhilox4_32_10_t state;
69
+ * curand_init(std::get<0>(seeds), // seed
70
+ * idx, // per-thread subsequence
71
+ * std::get<1>(seeds), // offset in subsequence
72
+ * &state);
73
+ * ...
74
+ * }
75
+ *
76
+ * host_caller(...) {
77
+ * PhiloxCudaState rng_engine_inputs;
78
+ * {
79
+ * // See Note [Acquire lock when using random generators]
80
+ * std::lock_guard<std::mutex> lock(gen->mutex_);
81
+ *
82
+ * // gen could be HostState or DevState here! No divergent code needed!
83
+ * rng_engine_inputs = gen->philox_cuda_state(offset_increment);
84
+ * }
85
+ * kernel<<<...>>>(..., rng_engine_inputs);
86
+ * }
87
+ *
88
+ */
89
+
90
+ struct TORCH_CUDA_CPP_API CUDAGeneratorImpl : public c10::GeneratorImpl {
91
+ // Constructors
92
+ CUDAGeneratorImpl(DeviceIndex device_index = -1);
93
+ ~CUDAGeneratorImpl() override = default;
94
+
95
+ // CUDAGeneratorImpl methods
96
+ std::shared_ptr<CUDAGeneratorImpl> clone() const;
97
+ void set_current_seed(uint64_t seed) override;
98
+ void set_offset(uint64_t offset) override;
99
+ uint64_t get_offset() const override;
100
+ uint64_t current_seed() const override;
101
+ uint64_t seed() override;
102
+ void set_state(const c10::TensorImpl& new_state) override;
103
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
104
+ void set_philox_offset_per_thread(uint64_t offset);
105
+ uint64_t philox_offset_per_thread() const;
106
+ void capture_prologue(int64_t* seed_extragraph, int64_t* offset_extragraph);
107
+ uint64_t capture_epilogue();
108
+ PhiloxCudaState philox_cuda_state(uint64_t increment);
109
+
110
+ bool reset_rnn_state() {
111
+ return !no_reset_rnn_state_.test_and_set();
112
+ }
113
+
114
+ // Temporarily accommodates call sites that use philox_engine_inputs.
115
+ // Allows incremental refactor of call sites to use philox_cuda_state.
116
+ std::pair<uint64_t, uint64_t> philox_engine_inputs(uint64_t increment);
117
+
118
+ static c10::DeviceType device_type();
119
+
120
+ private:
121
+ CUDAGeneratorImpl* clone_impl() const override;
122
+ uint64_t seed_ = default_rng_seed_val;
123
+ uint64_t philox_offset_per_thread_ = 0;
124
+ int64_t* seed_extragraph_{};
125
+ int64_t* offset_extragraph_{};
126
+ uint32_t offset_intragraph_ = 0;
127
+ bool graph_expects_this_gen_ = false;
128
+ std::atomic_flag no_reset_rnn_state_;
129
+ };
130
+
131
+ namespace cuda::detail {
132
+
133
+ TORCH_CUDA_CPP_API const Generator& getDefaultCUDAGenerator(
134
+ DeviceIndex device_index = -1);
135
+ TORCH_CUDA_CPP_API Generator createCUDAGenerator(DeviceIndex device_index = -1);
136
+
137
+ } // namespace cuda::detail
138
+ } // namespace at
shared/package-files/d6/d61cbd1738894ba8f836c0545ff843b578996848c9aca201b2ba8882dea2be43/_semi_structured_conversions.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ # This is PyTorch implementation of main part of reorder_meta()
5
+ # function, from tools/util/include/cutlass/util/host_reorder.h file
6
+ # of CUTLASS source tree. Furthermore, CUTLASS template for sparse
7
+ # GEMM decides upon layout of this matrix, and at the moment for the
8
+ # sparse GEMM executed on tensor cores, this is layout described by
9
+ # ColumnMajorInterleaved<2> data structure, in
10
+ # include/cutlass/layout/matrix.h of CUTLASS source tree. The
11
+ # reordering of meta matrix into meta_reordered matrix calculated
12
+ # according to these segments of CUTLASS code is re-implemented here.
13
+ # Note that this calculation produces offsets for scattering metadata
14
+ # matrix elements into reordered metadata matrix elements (or,
15
+ # equivalently, for gathering reordered metadata matrix element back
16
+ # into metadata matrix elements).
17
+ def _calculate_meta_reordering_scatter_offsets(m, meta_ncols, meta_dtype, device):
18
+ dst_rows = torch.arange(0, m, device=device)[:, None].repeat(1, meta_ncols)
19
+ dst_cols = torch.arange(0, meta_ncols, device=device).repeat(m, 1)
20
+
21
+ # Reorder the rows, then swizzle the 2x2 blocks.
22
+ group = 32 if meta_dtype.itemsize == 2 else 16
23
+ interweave = 4 if meta_dtype.itemsize == 2 else 2
24
+ dst_rows = (
25
+ dst_rows // group * group
26
+ + (dst_rows % 8) * interweave
27
+ + (dst_rows % group) // 8
28
+ )
29
+
30
+ topright = ((dst_rows % 2 == 0) & (dst_cols % 2 == 1)).to(torch.int8)
31
+ bottomleft = ((dst_rows % 2 == 1) & (dst_cols % 2 == 0)).to(torch.int8)
32
+ dst_rows += topright - bottomleft
33
+ dst_cols -= topright - bottomleft
34
+
35
+ # Assumed that meta tensor is to be stored in CUTLASS
36
+ # InterleavedColumnMajor layout, and reverse engineered
37
+ # corresponding code to store values into this tensor.
38
+ interleave = 2
39
+ cols_maj = dst_cols // interleave
40
+ cols_min = dst_cols % interleave
41
+ return (cols_maj * m * interleave + dst_rows * interleave + cols_min).view(-1)
42
+
43
+
44
+ # This function converts dense matrix into sparse semi-structured
45
+ # representation, producing "compressed" matrix, in the layout used by
46
+ # CUTLASS backend, and corresponding metadata matrix.
47
+ def sparse_semi_structured_from_dense_cutlass(dense):
48
+ if dense.dim() != 2:
49
+ raise RuntimeError(
50
+ f"Expected 2-dimensional dense tensor, got {dense.dim()}-dimensional tensor"
51
+ )
52
+
53
+ m, k = dense.shape
54
+ device = dense.device
55
+
56
+ meta_dtype = torch.int8
57
+ if dense.dtype == torch.int8:
58
+ meta_dtype = torch.int32
59
+ elif dense.dtype in [torch.half, torch.bfloat16, torch.float]:
60
+ meta_dtype = torch.int16
61
+ else:
62
+ raise RuntimeError(f"Invalid datatype {dense.dtype} of dense matrix")
63
+ quadbits_per_meta_elem = meta_dtype.itemsize * 8 // 4
64
+ if quadbits_per_meta_elem not in (4, 8):
65
+ raise RuntimeError("Invalid number of elements per meta element calculated")
66
+
67
+ if meta_dtype == torch.int32:
68
+ if m % 16 != 0:
69
+ raise RuntimeError(
70
+ f"Number of rows of dense matrix {m} must be divisible by 16"
71
+ )
72
+ else:
73
+ if m % 32 != 0:
74
+ raise RuntimeError(
75
+ f"Number of rows of dense matrix {m} must be divisible by 32"
76
+ )
77
+ if k % (4 * quadbits_per_meta_elem) != 0:
78
+ raise RuntimeError(
79
+ f"Number of columns of dense matrix {k} must be divisible by {4 * quadbits_per_meta_elem}"
80
+ )
81
+
82
+ if dense.dtype != torch.float:
83
+ ksparse = 4
84
+ dense_4 = dense.view(-1, k // ksparse, ksparse)
85
+ m0, m1, m2, m3 = (dense_4 != 0).unbind(-1)
86
+ else:
87
+ ksparse = 2
88
+ dense_2 = dense.view(-1, k // ksparse, ksparse)
89
+ m0, m2 = m1, m3 = (dense_2 != 0).unbind(-1)
90
+ meta_ncols = k // (ksparse * quadbits_per_meta_elem)
91
+
92
+ # Encoding quadruples of True/False values as follows:
93
+ # [True, True, False, False] -> 0b0100
94
+ # [True, False, True, False] -> 0b1000
95
+ # [False, True, True, False] -> 0b1001
96
+ # [True, False, False, True ] -> 0b1100
97
+ # [False, True, False, True ] -> 0b1101
98
+ # [False, False, True, True ] -> 0b1110
99
+ # Thus, lower two bits in the encoding are index of the True value
100
+ # at the lowest index in the quadruple, and the higher two bits in
101
+ # the encoding are index of the other True value in the quadruple.
102
+ # In case there are less than two True values, than False value or
103
+ # values at some index or indices are considered True for the
104
+ # encoding. In case there are more than two True values, then the
105
+ # excess True value(s) at some indices are considered False for
106
+ # the encoding. The exact encodings used for these cases are as
107
+ # follows:
108
+ # [False, False, False, False] -> 0b1110
109
+ # [False, False, False, True ] -> 0b1110
110
+ # [False, False, True, False] -> 0b1110
111
+ # [False, True, False, False] -> 0b1001
112
+ # [False, True, True, True ] -> 0b1101
113
+ # [True, False, False, False] -> 0b1000
114
+ # [True, False, True, True ] -> 0b1100
115
+ # [True, True, False, True ] -> 0b0100
116
+ # [True, True, True, False] -> 0b0100
117
+ # [True, True, True, True ] -> 0b0100
118
+ # These particular encodings are chosen, with the help of Espresso
119
+ # logic minimizer software, for the purpose of minimization of
120
+ # corresponding Boolean functions, that translate non-zero flags
121
+ # into encoding bits. Note also possible choices for the first
122
+ # and last of these encodings were limited only to (0b0100,
123
+ # 0b1110), in order to produce valid encodings for 1:2 sparsity
124
+ # case.
125
+
126
+ expr0 = m0 & m1
127
+ expr1 = ~m0 & m1
128
+ expr2 = ~m0 & ~m1
129
+ bit0 = expr1
130
+ bit1 = expr2
131
+ bit2 = expr0 | expr2 | m3
132
+ bit3 = expr1 | ~m1
133
+ idxs0 = bit0 | (bit1.to(torch.int64) << 1)
134
+ idxs1 = bit2 | (bit3.to(torch.int64) << 1)
135
+
136
+ if dense.dtype != torch.float:
137
+ sparse0 = dense_4.gather(-1, idxs0.unsqueeze(-1)) # type: ignore[possibly-undefined]
138
+ sparse1 = dense_4.gather(-1, idxs1.unsqueeze(-1))
139
+ sparse = torch.stack((sparse0, sparse1), dim=-1).view(m, k // 2)
140
+ else:
141
+ sparse = dense_2.gather(-1, idxs0.unsqueeze(-1) // 2).view(m, k // 2) # type: ignore[possibly-undefined]
142
+
143
+ meta_4 = idxs0 | (idxs1 << 2)
144
+ meta_n = meta_4.view((-1, meta_ncols, quadbits_per_meta_elem)).to(meta_dtype)
145
+
146
+ if quadbits_per_meta_elem == 4:
147
+ meta = (
148
+ meta_n[:, :, 0]
149
+ | (meta_n[:, :, 1] << 4)
150
+ | (meta_n[:, :, 2] << 8)
151
+ | (meta_n[:, :, 3] << 12)
152
+ )
153
+ elif quadbits_per_meta_elem == 8:
154
+ meta = (
155
+ meta_n[:, :, 0]
156
+ | (meta_n[:, :, 1] << 4)
157
+ | (meta_n[:, :, 2] << 8)
158
+ | (meta_n[:, :, 3] << 12)
159
+ | (meta_n[:, :, 4] << 16)
160
+ | (meta_n[:, :, 5] << 20)
161
+ | (meta_n[:, :, 6] << 24)
162
+ | (meta_n[:, :, 7] << 28)
163
+ )
164
+
165
+ # Reorder meta tensor elements.
166
+ meta_reordered = meta.new_empty((m * meta_ncols,)) # type: ignore[possibly-undefined]
167
+ meta_offsets = _calculate_meta_reordering_scatter_offsets(
168
+ m, meta_ncols, meta_dtype, device
169
+ )
170
+ meta_reordered.scatter_(0, meta_offsets, meta.view(-1))
171
+
172
+ return (sparse, meta_reordered.view(m, meta_ncols))
173
+
174
+
175
+ # This function performs reverse of the function above - it
176
+ # reconstructs dense matrix from a pair of "compressed" matrix, given
177
+ # in the layout used by CUTLASS backend, and accompanying metadata
178
+ # matrix.
179
+ def sparse_semi_structured_to_dense_cutlass(sparse, meta_reordered):
180
+ if sparse.dim() != 2:
181
+ raise RuntimeError(
182
+ f"Expected 2-dimensional sparse tensor, got {sparse.dim()}-dimensional tensor"
183
+ )
184
+
185
+ m, k = sparse.shape
186
+ device = sparse.device
187
+
188
+ if meta_reordered.dim() != 2:
189
+ raise RuntimeError(
190
+ f"Expected 2-dimensional meta tensor, got {meta_reordered.dim()}-dimensional tensor"
191
+ )
192
+ if meta_reordered.device != device:
193
+ raise RuntimeError(
194
+ f"Expected meta matrix to be on {device} device, got matrix on {meta_reordered.device} device"
195
+ )
196
+
197
+ meta_dtype = meta_reordered.dtype
198
+ if meta_dtype not in (torch.int16, torch.int32):
199
+ raise RuntimeError(f"Invalid datatype {meta_dtype} of meta matrix")
200
+ quadbits_per_meta_elem = meta_dtype.itemsize * 8 // 4
201
+
202
+ if sparse.dtype != torch.float:
203
+ ksparse = 4
204
+ else:
205
+ ksparse = 2
206
+
207
+ meta_nrows, meta_ncols = meta_reordered.shape
208
+ if meta_nrows != m:
209
+ raise RuntimeError(
210
+ f"Number of rows of meta matrix {meta_nrows} must be equal to number of columns of spase matrix {m}"
211
+ )
212
+ if meta_ncols * ksparse * quadbits_per_meta_elem != 2 * k:
213
+ raise RuntimeError(
214
+ f"Number of columns of sparse matrix {k} different from the {meta_ncols * ksparse * quadbits_per_meta_elem // 2}, "
215
+ "expected according to the number of columns of meta matrix"
216
+ )
217
+
218
+ # Undo meta tensor elements reordering.
219
+ meta_offsets = _calculate_meta_reordering_scatter_offsets(
220
+ m, meta_ncols, meta_dtype, device
221
+ )
222
+ meta = torch.gather(meta_reordered.view(-1), 0, meta_offsets).view(m, meta_ncols)
223
+
224
+ # Unpack sparse tensor back to original dense tensor, using
225
+ # information provided by meta tensor. Note that torch.float
226
+ # datatype is handled pretty much the same as
227
+ # torch.half/torch.bfloat16, as metadata for a pair of torch.float
228
+ # value is encoded as if underlying 8 bytes contain four
229
+ # torch.half/torch.bfloat16 values, where either first two or last
230
+ # two are zeros.
231
+ meta_2 = torch.empty(
232
+ (m, meta_ncols, 2 * quadbits_per_meta_elem),
233
+ dtype=meta_dtype,
234
+ device=device,
235
+ )
236
+ if quadbits_per_meta_elem == 4:
237
+ meta_2[:, :, 0] = meta & 0b11
238
+ meta_2[:, :, 1] = (meta >> 2) & 0b11
239
+ meta_2[:, :, 2] = (meta >> 4) & 0b11
240
+ meta_2[:, :, 3] = (meta >> 6) & 0b11
241
+ meta_2[:, :, 4] = (meta >> 8) & 0b11
242
+ meta_2[:, :, 5] = (meta >> 10) & 0b11
243
+ meta_2[:, :, 6] = (meta >> 12) & 0b11
244
+ meta_2[:, :, 7] = (meta >> 14) & 0b11
245
+ elif quadbits_per_meta_elem == 8:
246
+ meta_2[:, :, 0] = meta & 0b11
247
+ meta_2[:, :, 1] = (meta >> 2) & 0b11
248
+ meta_2[:, :, 2] = (meta >> 4) & 0b11
249
+ meta_2[:, :, 3] = (meta >> 6) & 0b11
250
+ meta_2[:, :, 4] = (meta >> 8) & 0b11
251
+ meta_2[:, :, 5] = (meta >> 10) & 0b11
252
+ meta_2[:, :, 6] = (meta >> 12) & 0b11
253
+ meta_2[:, :, 7] = (meta >> 14) & 0b11
254
+ meta_2[:, :, 8] = (meta >> 16) & 0b11
255
+ meta_2[:, :, 9] = (meta >> 18) & 0b11
256
+ meta_2[:, :, 10] = (meta >> 20) & 0b11
257
+ meta_2[:, :, 11] = (meta >> 22) & 0b11
258
+ meta_2[:, :, 12] = (meta >> 24) & 0b11
259
+ meta_2[:, :, 13] = (meta >> 26) & 0b11
260
+ meta_2[:, :, 14] = (meta >> 28) & 0b11
261
+ meta_2[:, :, 15] = (meta >> 30) & 0b11
262
+
263
+ dense_offsets = meta_2.view(-1) + (
264
+ torch.arange(0, 2 * m * k // ksparse, device=device) * 4
265
+ ).view(-1, 1).repeat(1, 2).view(-1)
266
+
267
+ dense = torch.zeros((m * 2 * k,), dtype=sparse.dtype, device=device)
268
+ if sparse.dtype != torch.float:
269
+ dense.scatter_(0, dense_offsets, sparse.view(-1))
270
+ else:
271
+ dense.view(torch.half).scatter_(
272
+ 0, dense_offsets, sparse.view(torch.half).view(-1)
273
+ )
274
+
275
+ return dense.view(m, 2 * k)
shared/package-files/d6/d61cf1c1a30d2506cc308ae812295e691a24a866cb3fc860177e4152bedda3d2/binary_cross_entropy_backward_native.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor binary_cross_entropy_backward_cpu(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean);
20
+ TORCH_API at::Tensor & binary_cross_entropy_backward_out_cpu(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, at::Tensor & grad_input);
21
+ TORCH_API at::Tensor binary_cross_entropy_backward_cuda(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean);
22
+ TORCH_API at::Tensor & binary_cross_entropy_backward_out_cuda(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const c10::optional<at::Tensor> & weight, int64_t reduction, at::Tensor & grad_input);
23
+ } // namespace native
24
+ } // namespace at
shared/package-files/d6/d6299b00fb957aeff2f9dd718a5f4c25471e6e51704738855a1391ad7e676796/results_exact_initial_local_linear_trend_R.csv ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "r_1","r_2","r0_1","r0_2","r1_1","r1_2","sumN","sumN0","sumN1","sumN2","m_1","v_1","F_1","Finf_1","a_1","a_2","sumP","sumPinf","att_1","att_2","sumPtt","alphahat_1","alphahat_2","sumV","muhat_1","sumVmu","etahat_1","etahat_2","sumVeta","epshat_1","Veps_1","llf"
2
+ 0,0,0,0,9.72422585109483,-2.4212757752195,0,0,2,-4.1254118726452,0,10.2394,1.993,1,0,0,0,2,10.2394,0,0.9965,9.72422585109483,-2.4212757752195,4.1254118726452,9.72422585109483,1.78897970994046,-2.13333279022294,0.603319851251709,8.78748511553388,0.515174148905165,1.78897970994046,-21.1364983872324
3
+ 0,0,-0.258491795737664,0.258491795737664,-2.4212757752195,0,0,0,1,-3.71701622659957,10.2394,-6.0355,12.239,1,10.2394,0,12.58,4,4.2039,-6.0355,9.2795,5.16961728565239,-1.81795592396779,3.93514567728326,5.16961728565239,1.47322425474258,1.86569619045403,0.0756893037514425,8.05444975507323,-0.965717285652394,1.47322425474258,NA
4
+ 0.226062788132076,0.032429007605588,0.226062788132076,0.032429007605588,0,0,0.051363991244706,0.051363991244706,0,0,-1.8316,7.954723,30.798,NA,-1.8316,-6.0355,78.844,NA,5.60835701068251,-1.75671757198519,13.749163922982,5.21735755213863,-1.74226662021634,3.60076175360198,5.21735755213863,1.47286280067942,-1.88507262098594,0.608799626952847,7.4387710112529,0.905765447861367,1.47286280067943,NA
5
+ -0.228410592631279,0.260839600236867,NA,NA,NA,NA,0.080687059729398,NA,NA,NA,3.85163943869732,-2.85163943869732,22.250346743295,NA,3.85163943869732,-1.75671757198519,48.7242243976881,NA,1.25542601501419,-2.91892501722355,9.16473520710951,1.59001831093635,-1.1334669932635,3.44977255623722,1.59001831093635,1.47107882801791,0.558189356012382,0.45094018712092,7.18360558861604,-0.590018310936346,1.47107882801791,NA
6
+ 0.0676347214361302,0.193204878800737,NA,NA,NA,NA,0.0918518103125956,NA,NA,NA,-1.66349900220936,2.66349900220936,20.3194339439886,NA,-1.66349900220936,-2.91892501722355,42.1882350771407,NA,0.73875485281549,-1.94280306025839,8.10697982907794,1.01474067368523,-0.682526806142577,3.40417641537387,1.01474067368523,1.47005925030176,0.61923038959202,0.275817961347531,7.09409485861663,-0.0147406736852317,1.47005925030176,NA
7
+ 0.0750309450614346,0.118173933739302,NA,NA,NA,NA,0.0953539315927209,NA,NA,NA,-1.2040482074429,2.2040482074429,19.7436685873651,NA,-1.2040482074429,-1.94280306025839,40.2635281749167,NA,0.777515102727931,-1.16474757404214,7.78903665265676,0.951444257134675,-0.406708844795046,3.41779499251488,0.951444257134675,1.47005925030176,0.41816137510756,0.157559310008498,7.06776435408301,0.0485557428653252,1.47005925030176,NA
8
+ 0.0506678026302629,0.0675061311090392,NA,NA,NA,NA,0.0953539315927209,NA,NA,NA,-0.387232471314205,1.38723247131421,19.5578741215719,NA,-0.387232471314205,-1.16474757404214,39.6448274460767,NA,0.858637278359423,-0.681255709019103,7.68611246288461,0.962896787447189,-0.249149534786548,3.51108468447222,0.962896787447189,1.47107882801791,0.264517213944311,0.0827521880715023,7.06946955440421,0.0371032125528116,1.47107882801791,NA
9
+ 0.032051037676519,0.0354550934325202,NA,NA,NA,NA,0.0918518103125956,NA,NA,NA,0.17738156934032,0.82261843065968,19.4963427441272,NA,0.17738156934032,-0.681255709019103,39.4401675462981,NA,0.915908406318996,-0.395782473854191,7.65198356932808,0.978264466604951,-0.166397346715046,3.81786955269073,0.978264466604951,1.47286280067943,0.174510511932601,0.0333995242097925,7.08451748207039,0.0217355333950489,1.47286280067943,NA
10
+ 0.0211451001978191,0.0143099932347011,NA,NA,NA,NA,0.080687059729398,NA,NA,NA,0.520125932464805,0.479874067535195,19.4757829323051,NA,0.520125932464805,-0.395782473854191,39.3718080383884,NA,0.950893423903834,-0.229493137203491,7.64057446288005,0.986377631822506,-0.132997822505254,4.85378169531128,0.986377631822506,1.47322425474257,0.118100374165989,0,7.08849536606466,0.0136223681774941,1.47322425474258,NA
11
+ 0.0143099932347011,0,NA,NA,NA,NA,0.051363991244706,NA,NA,NA,0.721400286700344,0.278599713299656,19.4688920344185,NA,0.721400286700344,-0.229493137203491,39.3488989452308,NA,0.971480183483241,-0.132997822505254,7.63674986537858,0.971480183483241,-0.132997822505254,9.22058000043485,0.971480183483241,1.78897970994046,0,0,10.587,0.0285198165167594,1.78897970994046,NA
12
+ 0,0,NA,NA,NA,NA,0,NA,NA,NA,NA,NA,NA,NA,0.838482360977987,-0.132997822505254,39.3412127441284,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA
shared/package-files/d6/d62e704a0000340ef3d7def67fd9b42f2b5e112734e3293de037e703cea2ad70/att5420-nl ADDED
Binary file (1.38 kB). View file
 
shared/package-files/d6/d6318382b231dfe4d638234c482e33c6665aecb1f2314ebd0d7877875d818da8/test_spectral_bipartivity.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ pytest.importorskip("scipy")
4
+
5
+ import networkx as nx
6
+ from networkx.algorithms.bipartite import spectral_bipartivity as sb
7
+
8
+ # Examples from Figure 1
9
+ # E. Estrada and J. A. Rodríguez-Velázquez, "Spectral measures of
10
+ # bipartivity in complex networks", PhysRev E 72, 046105 (2005)
11
+
12
+
13
+ class TestSpectralBipartivity:
14
+ def test_star_like(self):
15
+ # star-like
16
+
17
+ G = nx.star_graph(2)
18
+ G.add_edge(1, 2)
19
+ assert sb(G) == pytest.approx(0.843, abs=1e-3)
20
+
21
+ G = nx.star_graph(3)
22
+ G.add_edge(1, 2)
23
+ assert sb(G) == pytest.approx(0.871, abs=1e-3)
24
+
25
+ G = nx.star_graph(4)
26
+ G.add_edge(1, 2)
27
+ assert sb(G) == pytest.approx(0.890, abs=1e-3)
28
+
29
+ def test_k23_like(self):
30
+ # K2,3-like
31
+ G = nx.complete_bipartite_graph(2, 3)
32
+ G.add_edge(0, 1)
33
+ assert sb(G) == pytest.approx(0.769, abs=1e-3)
34
+
35
+ G = nx.complete_bipartite_graph(2, 3)
36
+ G.add_edge(2, 4)
37
+ assert sb(G) == pytest.approx(0.829, abs=1e-3)
38
+
39
+ G = nx.complete_bipartite_graph(2, 3)
40
+ G.add_edge(2, 4)
41
+ G.add_edge(3, 4)
42
+ assert sb(G) == pytest.approx(0.731, abs=1e-3)
43
+
44
+ G = nx.complete_bipartite_graph(2, 3)
45
+ G.add_edge(0, 1)
46
+ G.add_edge(2, 4)
47
+ assert sb(G) == pytest.approx(0.692, abs=1e-3)
48
+
49
+ G = nx.complete_bipartite_graph(2, 3)
50
+ G.add_edge(2, 4)
51
+ G.add_edge(3, 4)
52
+ G.add_edge(0, 1)
53
+ assert sb(G) == pytest.approx(0.645, abs=1e-3)
54
+
55
+ G = nx.complete_bipartite_graph(2, 3)
56
+ G.add_edge(2, 4)
57
+ G.add_edge(3, 4)
58
+ G.add_edge(2, 3)
59
+ assert sb(G) == pytest.approx(0.645, abs=1e-3)
60
+
61
+ G = nx.complete_bipartite_graph(2, 3)
62
+ G.add_edge(2, 4)
63
+ G.add_edge(3, 4)
64
+ G.add_edge(2, 3)
65
+ G.add_edge(0, 1)
66
+ assert sb(G) == pytest.approx(0.597, abs=1e-3)
67
+
68
+ def test_single_nodes(self):
69
+ # single nodes
70
+ G = nx.complete_bipartite_graph(2, 3)
71
+ G.add_edge(2, 4)
72
+ sbn = sb(G, nodes=[1, 2])
73
+ assert sbn[1] == pytest.approx(0.85, abs=1e-2)
74
+ assert sbn[2] == pytest.approx(0.77, abs=1e-2)
75
+
76
+ G = nx.complete_bipartite_graph(2, 3)
77
+ G.add_edge(0, 1)
78
+ sbn = sb(G, nodes=[1, 2])
79
+ assert sbn[1] == pytest.approx(0.73, abs=1e-2)
80
+ assert sbn[2] == pytest.approx(0.82, abs=1e-2)
shared/package-files/d6/d63221cd4ede06f637a5b5b72d9a09842394d8a5aa82dcb91e043a541608a795/utils.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import stat
4
+ import select
5
+ import time
6
+ import errno
7
+
8
+ try:
9
+ InterruptedError
10
+ except NameError:
11
+ # Alias Python2 exception to Python3
12
+ InterruptedError = select.error
13
+
14
+ if sys.version_info[0] >= 3:
15
+ string_types = (str,)
16
+ else:
17
+ string_types = (unicode, str)
18
+
19
+
20
+ def is_executable_file(path):
21
+ """Checks that path is an executable regular file, or a symlink towards one.
22
+
23
+ This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
24
+ """
25
+ # follow symlinks,
26
+ fpath = os.path.realpath(path)
27
+
28
+ if not os.path.isfile(fpath):
29
+ # non-files (directories, fifo, etc.)
30
+ return False
31
+
32
+ mode = os.stat(fpath).st_mode
33
+
34
+ if (sys.platform.startswith('sunos')
35
+ and os.getuid() == 0):
36
+ # When root on Solaris, os.X_OK is True for *all* files, irregardless
37
+ # of their executability -- instead, any permission bit of any user,
38
+ # group, or other is fine enough.
39
+ #
40
+ # (This may be true for other "Unix98" OS's such as HP-UX and AIX)
41
+ return bool(mode & (stat.S_IXUSR |
42
+ stat.S_IXGRP |
43
+ stat.S_IXOTH))
44
+
45
+ return os.access(fpath, os.X_OK)
46
+
47
+
48
+ def which(filename, env=None):
49
+ '''This takes a given filename; tries to find it in the environment path;
50
+ then checks if it is executable. This returns the full path to the filename
51
+ if found and executable. Otherwise this returns None.'''
52
+
53
+ # Special case where filename contains an explicit path.
54
+ if os.path.dirname(filename) != '' and is_executable_file(filename):
55
+ return filename
56
+ if env is None:
57
+ env = os.environ
58
+ p = env.get('PATH')
59
+ if not p:
60
+ p = os.defpath
61
+ pathlist = p.split(os.pathsep)
62
+ for path in pathlist:
63
+ ff = os.path.join(path, filename)
64
+ if is_executable_file(ff):
65
+ return ff
66
+ return None
67
+
68
+
69
+ def split_command_line(command_line):
70
+
71
+ '''This splits a command line into a list of arguments. It splits arguments
72
+ on spaces, but handles embedded quotes, doublequotes, and escaped
73
+ characters. It's impossible to do this with a regular expression, so I
74
+ wrote a little state machine to parse the command line. '''
75
+
76
+ arg_list = []
77
+ arg = ''
78
+
79
+ # Constants to name the states we can be in.
80
+ state_basic = 0
81
+ state_esc = 1
82
+ state_singlequote = 2
83
+ state_doublequote = 3
84
+ # The state when consuming whitespace between commands.
85
+ state_whitespace = 4
86
+ state = state_basic
87
+
88
+ for c in command_line:
89
+ if state == state_basic or state == state_whitespace:
90
+ if c == '\\':
91
+ # Escape the next character
92
+ state = state_esc
93
+ elif c == r"'":
94
+ # Handle single quote
95
+ state = state_singlequote
96
+ elif c == r'"':
97
+ # Handle double quote
98
+ state = state_doublequote
99
+ elif c.isspace():
100
+ # Add arg to arg_list if we aren't in the middle of whitespace.
101
+ if state == state_whitespace:
102
+ # Do nothing.
103
+ None
104
+ else:
105
+ arg_list.append(arg)
106
+ arg = ''
107
+ state = state_whitespace
108
+ else:
109
+ arg = arg + c
110
+ state = state_basic
111
+ elif state == state_esc:
112
+ arg = arg + c
113
+ state = state_basic
114
+ elif state == state_singlequote:
115
+ if c == r"'":
116
+ state = state_basic
117
+ else:
118
+ arg = arg + c
119
+ elif state == state_doublequote:
120
+ if c == r'"':
121
+ state = state_basic
122
+ else:
123
+ arg = arg + c
124
+
125
+ if arg != '':
126
+ arg_list.append(arg)
127
+ return arg_list
128
+
129
+
130
+ def select_ignore_interrupts(iwtd, owtd, ewtd, timeout=None):
131
+
132
+ '''This is a wrapper around select.select() that ignores signals. If
133
+ select.select raises a select.error exception and errno is an EINTR
134
+ error then it is ignored. Mainly this is used to ignore sigwinch
135
+ (terminal resize). '''
136
+
137
+ # if select() is interrupted by a signal (errno==EINTR) then
138
+ # we loop back and enter the select() again.
139
+ if timeout is not None:
140
+ end_time = time.time() + timeout
141
+ while True:
142
+ try:
143
+ return select.select(iwtd, owtd, ewtd, timeout)
144
+ except InterruptedError:
145
+ err = sys.exc_info()[1]
146
+ if err.args[0] == errno.EINTR:
147
+ # if we loop back we have to subtract the
148
+ # amount of time we already waited.
149
+ if timeout is not None:
150
+ timeout = end_time - time.time()
151
+ if timeout < 0:
152
+ return([], [], [])
153
+ else:
154
+ # something else caused the select.error, so
155
+ # this actually is an exception.
156
+ raise
157
+
158
+
159
+ def poll_ignore_interrupts(fds, timeout=None):
160
+ '''Simple wrapper around poll to register file descriptors and
161
+ ignore signals.'''
162
+
163
+ if timeout is not None:
164
+ end_time = time.time() + timeout
165
+
166
+ poller = select.poll()
167
+ for fd in fds:
168
+ poller.register(fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR)
169
+
170
+ while True:
171
+ try:
172
+ timeout_ms = None if timeout is None else timeout * 1000
173
+ results = poller.poll(timeout_ms)
174
+ return [afd for afd, _ in results]
175
+ except InterruptedError:
176
+ err = sys.exc_info()[1]
177
+ if err.args[0] == errno.EINTR:
178
+ # if we loop back we have to subtract the
179
+ # amount of time we already waited.
180
+ if timeout is not None:
181
+ timeout = end_time - time.time()
182
+ if timeout < 0:
183
+ return []
184
+ else:
185
+ # something else caused the select.error, so
186
+ # this actually is an exception.
187
+ raise
shared/package-files/d6/d635f1005b25da2bd7953f52b0638ceecd6ebd2d94284b96ccd600fdb4ed4ba5/contains.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S
2
+ from sympy.core.relational import Eq, Ne
3
+ from sympy.logic.boolalg import BooleanFunction
4
+ from sympy.utilities.misc import func_name
5
+ from .sets import Set
6
+
7
+
8
+ class Contains(BooleanFunction):
9
+ """
10
+ Asserts that x is an element of the set S.
11
+
12
+ Examples
13
+ ========
14
+
15
+ >>> from sympy import Symbol, Integer, S, Contains
16
+ >>> Contains(Integer(2), S.Integers)
17
+ True
18
+ >>> Contains(Integer(-2), S.Naturals)
19
+ False
20
+ >>> i = Symbol('i', integer=True)
21
+ >>> Contains(i, S.Naturals)
22
+ Contains(i, Naturals)
23
+
24
+ References
25
+ ==========
26
+
27
+ .. [1] https://en.wikipedia.org/wiki/Element_%28mathematics%29
28
+ """
29
+ @classmethod
30
+ def eval(cls, x, s):
31
+
32
+ if not isinstance(s, Set):
33
+ raise TypeError('expecting Set, not %s' % func_name(s))
34
+
35
+ ret = s.contains(x)
36
+ if not isinstance(ret, Contains) and (
37
+ ret in (S.true, S.false) or isinstance(ret, Set)):
38
+ return ret
39
+
40
+ @property
41
+ def binary_symbols(self):
42
+ return set().union(*[i.binary_symbols
43
+ for i in self.args[1].args
44
+ if i.is_Boolean or i.is_Symbol or
45
+ isinstance(i, (Eq, Ne))])
46
+
47
+ def as_set(self):
48
+ return self.args[1]
shared/package-files/d6/d6373e1408ef90a9e60a3873f3ec908042ab37fb159b3022f03568cbdfcaf004/Casey ADDED
Binary file (287 Bytes). View file
 
shared/package-files/d6/d63e4b7887f677be27d65cef98e4133d3bab49f264d85230576a1cf00f071416/group_norm_expanded_weights.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import reduce
2
+ import operator
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from .expanded_weights_impl import ExpandedWeight, implements_per_sample_grads
6
+ from .expanded_weights_utils import standard_kwargs, \
7
+ forward_helper, set_grad_sample_if_exists, unpack_expanded_weight_or_tensor
8
+ from typing import List, Optional
9
+
10
+ @implements_per_sample_grads(F.group_norm)
11
+ class GroupNormPerSampleGrad(torch.autograd.Function):
12
+ @staticmethod
13
+ def forward(ctx, kwarg_names, _, *expanded_args_and_kwargs):
14
+ expanded_args, expanded_kwargs = standard_kwargs(kwarg_names, expanded_args_and_kwargs)
15
+ input, num_groups = expanded_args
16
+ N = input.shape[0]
17
+ C = input.shape[1]
18
+ HxW = reduce(operator.mul, input.shape[2:], 1)
19
+ weight, bias, eps = expanded_kwargs['weight'], expanded_kwargs['bias'], expanded_kwargs['eps']
20
+ output, mean, rstd = forward_helper(torch.native_group_norm, (input, weight, bias, N, C, HxW, num_groups, eps), {})
21
+ ctx.input, ctx.num_groups = input, num_groups
22
+ ctx.weight, ctx.eps = weight, eps
23
+ ctx.mean, ctx.rstd = mean, rstd
24
+ if isinstance(bias, ExpandedWeight):
25
+ ctx.bias = bias
26
+ if input.requires_grad and isinstance(weight, ExpandedWeight):
27
+ ctx.weight = weight
28
+ return output
29
+
30
+ @staticmethod
31
+ def backward(ctx, grad_output):
32
+ input, num_groups = ctx.input, ctx.num_groups
33
+ weight, bias, eps = ctx.weight, ctx.bias, ctx.eps
34
+ mean, rstd = ctx.mean, ctx.rstd
35
+
36
+ results: List[Optional[torch.Tensor]] = []
37
+ results.append(None) # for kwarg names
38
+ results.append(None) # for op reference
39
+
40
+ if input.requires_grad:
41
+ weight_c = unpack_expanded_weight_or_tensor(weight, lambda t: t.contiguous())
42
+ input_c = input.contiguous()
43
+ grad_output_c = grad_output.contiguous() if grad_output is not None else None
44
+ N = input.shape[0]
45
+ C = input.shape[1]
46
+ HxW = 1
47
+ for s in input.shape[2:]:
48
+ HxW *= s
49
+ bw_fn = torch.ops.aten.native_group_norm_backward
50
+ results.append(bw_fn(grad_output_c, input_c,
51
+ mean, rstd, weight_c, N, C, HxW, num_groups, (True, False, False))[0])
52
+ else:
53
+ results.append(None)
54
+
55
+ # weight and bias don't compute batched gradients; no other arguments are differentiable
56
+ results = results + [None] * 4
57
+
58
+ # set grad_sample field for weight and bias with per sample gradients
59
+ if hasattr(ctx, "weight"):
60
+ set_grad_sample_if_exists(weight,
61
+ lambda _: torch.einsum("ni...->ni", F.group_norm(input, num_groups, eps=eps) * grad_output))
62
+ if hasattr(ctx, "bias"):
63
+ set_grad_sample_if_exists(bias, lambda _: torch.einsum("ni...->ni", grad_output))
64
+ return tuple(results)
shared/package-files/d6/d63eb28e9e3f5a5c5c0d748128e93e21fac46d6b42e07bdb2081de336c76e72b/test_to_timestamp.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import timedelta
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas import (
7
+ DataFrame,
8
+ DatetimeIndex,
9
+ PeriodIndex,
10
+ Series,
11
+ Timedelta,
12
+ date_range,
13
+ period_range,
14
+ to_datetime,
15
+ )
16
+ import pandas._testing as tm
17
+
18
+
19
+ def _get_with_delta(delta, freq="YE-DEC"):
20
+ return date_range(
21
+ to_datetime("1/1/2001") + delta,
22
+ to_datetime("12/31/2009") + delta,
23
+ freq=freq,
24
+ )
25
+
26
+
27
+ class TestToTimestamp:
28
+ def test_to_timestamp(self, frame_or_series):
29
+ K = 5
30
+ index = period_range(freq="Y", start="1/1/2001", end="12/1/2009")
31
+ obj = DataFrame(
32
+ np.random.default_rng(2).standard_normal((len(index), K)),
33
+ index=index,
34
+ columns=["A", "B", "C", "D", "E"],
35
+ )
36
+ obj["mix"] = "a"
37
+ obj = tm.get_obj(obj, frame_or_series)
38
+
39
+ exp_index = date_range("1/1/2001", end="12/31/2009", freq="YE-DEC")
40
+ exp_index = exp_index + Timedelta(1, "D") - Timedelta(1, "ns")
41
+ result = obj.to_timestamp("D", "end")
42
+ tm.assert_index_equal(result.index, exp_index)
43
+ tm.assert_numpy_array_equal(result.values, obj.values)
44
+ if frame_or_series is Series:
45
+ assert result.name == "A"
46
+
47
+ exp_index = date_range("1/1/2001", end="1/1/2009", freq="YS-JAN")
48
+ result = obj.to_timestamp("D", "start")
49
+ tm.assert_index_equal(result.index, exp_index)
50
+
51
+ result = obj.to_timestamp(how="start")
52
+ tm.assert_index_equal(result.index, exp_index)
53
+
54
+ delta = timedelta(hours=23)
55
+ result = obj.to_timestamp("H", "end")
56
+ exp_index = _get_with_delta(delta)
57
+ exp_index = exp_index + Timedelta(1, "h") - Timedelta(1, "ns")
58
+ tm.assert_index_equal(result.index, exp_index)
59
+
60
+ delta = timedelta(hours=23, minutes=59)
61
+ result = obj.to_timestamp("T", "end")
62
+ exp_index = _get_with_delta(delta)
63
+ exp_index = exp_index + Timedelta(1, "m") - Timedelta(1, "ns")
64
+ tm.assert_index_equal(result.index, exp_index)
65
+
66
+ result = obj.to_timestamp("S", "end")
67
+ delta = timedelta(hours=23, minutes=59, seconds=59)
68
+ exp_index = _get_with_delta(delta)
69
+ exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
70
+ tm.assert_index_equal(result.index, exp_index)
71
+
72
+ def test_to_timestamp_columns(self):
73
+ K = 5
74
+ index = period_range(freq="Y", start="1/1/2001", end="12/1/2009")
75
+ df = DataFrame(
76
+ np.random.default_rng(2).standard_normal((len(index), K)),
77
+ index=index,
78
+ columns=["A", "B", "C", "D", "E"],
79
+ )
80
+ df["mix"] = "a"
81
+
82
+ # columns
83
+ df = df.T
84
+
85
+ exp_index = date_range("1/1/2001", end="12/31/2009", freq="YE-DEC")
86
+ exp_index = exp_index + Timedelta(1, "D") - Timedelta(1, "ns")
87
+ result = df.to_timestamp("D", "end", axis=1)
88
+ tm.assert_index_equal(result.columns, exp_index)
89
+ tm.assert_numpy_array_equal(result.values, df.values)
90
+
91
+ exp_index = date_range("1/1/2001", end="1/1/2009", freq="YS-JAN")
92
+ result = df.to_timestamp("D", "start", axis=1)
93
+ tm.assert_index_equal(result.columns, exp_index)
94
+
95
+ delta = timedelta(hours=23)
96
+ result = df.to_timestamp("H", "end", axis=1)
97
+ exp_index = _get_with_delta(delta)
98
+ exp_index = exp_index + Timedelta(1, "h") - Timedelta(1, "ns")
99
+ tm.assert_index_equal(result.columns, exp_index)
100
+
101
+ delta = timedelta(hours=23, minutes=59)
102
+ result = df.to_timestamp("min", "end", axis=1)
103
+ exp_index = _get_with_delta(delta)
104
+ exp_index = exp_index + Timedelta(1, "m") - Timedelta(1, "ns")
105
+ tm.assert_index_equal(result.columns, exp_index)
106
+
107
+ result = df.to_timestamp("S", "end", axis=1)
108
+ delta = timedelta(hours=23, minutes=59, seconds=59)
109
+ exp_index = _get_with_delta(delta)
110
+ exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
111
+ tm.assert_index_equal(result.columns, exp_index)
112
+
113
+ result1 = df.to_timestamp("5min", axis=1)
114
+ result2 = df.to_timestamp("min", axis=1)
115
+ expected = date_range("2001-01-01", "2009-01-01", freq="YS")
116
+ assert isinstance(result1.columns, DatetimeIndex)
117
+ assert isinstance(result2.columns, DatetimeIndex)
118
+ tm.assert_numpy_array_equal(result1.columns.asi8, expected.asi8)
119
+ tm.assert_numpy_array_equal(result2.columns.asi8, expected.asi8)
120
+ # PeriodIndex.to_timestamp always use 'infer'
121
+ assert result1.columns.freqstr == "YS-JAN"
122
+ assert result2.columns.freqstr == "YS-JAN"
123
+
124
+ def test_to_timestamp_invalid_axis(self):
125
+ index = period_range(freq="Y", start="1/1/2001", end="12/1/2009")
126
+ obj = DataFrame(
127
+ np.random.default_rng(2).standard_normal((len(index), 5)), index=index
128
+ )
129
+
130
+ # invalid axis
131
+ with pytest.raises(ValueError, match="axis"):
132
+ obj.to_timestamp(axis=2)
133
+
134
+ def test_to_timestamp_hourly(self, frame_or_series):
135
+ index = period_range(freq="h", start="1/1/2001", end="1/2/2001")
136
+ obj = Series(1, index=index, name="foo")
137
+ if frame_or_series is not Series:
138
+ obj = obj.to_frame()
139
+
140
+ exp_index = date_range("1/1/2001 00:59:59", end="1/2/2001 00:59:59", freq="h")
141
+ result = obj.to_timestamp(how="end")
142
+ exp_index = exp_index + Timedelta(1, "s") - Timedelta(1, "ns")
143
+ tm.assert_index_equal(result.index, exp_index)
144
+ if frame_or_series is Series:
145
+ assert result.name == "foo"
146
+
147
+ def test_to_timestamp_raises(self, index, frame_or_series):
148
+ # GH#33327
149
+ obj = frame_or_series(index=index, dtype=object)
150
+
151
+ if not isinstance(index, PeriodIndex):
152
+ msg = f"unsupported Type {type(index).__name__}"
153
+ with pytest.raises(TypeError, match=msg):
154
+ obj.to_timestamp()
shared/package-files/d6/d63fa4403cf0fe8a47451939edb425f1d3f9005ee0f2333f12e76bb2c53979c5/constant_propagation.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/jit/ir/ir.h>
4
+
5
+ namespace torch {
6
+ namespace jit {
7
+
8
+ // Runs constant propagation on all objects unless ignore_custom_classes is
9
+ // specified as true, in which case user defined classes are skipped. This is
10
+ // useful to prevent early fusion of packing operations, which end up lowering
11
+ // away information about their constructors (e.g. packed::linear_clamp_prepack
12
+ // and prepacked::conv2d_clamp_prepack)
13
+ // Returns True if the pass made a change to the graph
14
+ TORCH_API bool ConstantPropagation(
15
+ std::shared_ptr<Graph>& graph,
16
+ bool ignore_custom_classes = false);
17
+
18
+ // runs constant propagation only on ops that have non-aliasing inputs & outputs
19
+ // Returns True if the pass made a change to the graph
20
+ TORCH_API bool ConstantPropagationImmutableTypes(std::shared_ptr<Graph>& graph);
21
+
22
+ // Runs the node if its inputs are constants. Callers of this function must
23
+ // make their own determination if constant prop is appropriate - for example
24
+ // non-deterministic ops or ops with side effects. If ignore_custom_classes is
25
+ // specified, nodes that output user defined classes are not run.
26
+ TORCH_API c10::optional<Stack> runNodeIfInputsAreConstant(
27
+ const Node* node,
28
+ bool ignore_custom_classes = false,
29
+ AliasDb* db = nullptr);
30
+
31
+ } // namespace jit
32
+ } // namespace torch
shared/package-files/d6/d64431841511ea36f8fcaa8040769fdbdced56a386692807193dbc8301fe2ac8/test_to_csv.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from io import StringIO
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ import pandas as pd
8
+ from pandas import Series
9
+ import pandas._testing as tm
10
+
11
+ from pandas.io.common import get_handle
12
+
13
+
14
+ class TestSeriesToCSV:
15
+ def read_csv(self, path, **kwargs):
16
+ params = {"index_col": 0, "header": None}
17
+ params.update(**kwargs)
18
+
19
+ header = params.get("header")
20
+ out = pd.read_csv(path, **params).squeeze("columns")
21
+
22
+ if header is None:
23
+ out.name = out.index.name = None
24
+
25
+ return out
26
+
27
+ def test_from_csv(self, datetime_series, string_series):
28
+ # freq doesn't round-trip
29
+ datetime_series.index = datetime_series.index._with_freq(None)
30
+
31
+ with tm.ensure_clean() as path:
32
+ datetime_series.to_csv(path, header=False)
33
+ ts = self.read_csv(path, parse_dates=True)
34
+ tm.assert_series_equal(datetime_series, ts, check_names=False)
35
+
36
+ assert ts.name is None
37
+ assert ts.index.name is None
38
+
39
+ # see gh-10483
40
+ datetime_series.to_csv(path, header=True)
41
+ ts_h = self.read_csv(path, header=0)
42
+ assert ts_h.name == "ts"
43
+
44
+ string_series.to_csv(path, header=False)
45
+ series = self.read_csv(path)
46
+ tm.assert_series_equal(string_series, series, check_names=False)
47
+
48
+ assert series.name is None
49
+ assert series.index.name is None
50
+
51
+ string_series.to_csv(path, header=True)
52
+ series_h = self.read_csv(path, header=0)
53
+ assert series_h.name == "series"
54
+
55
+ with open(path, "w", encoding="utf-8") as outfile:
56
+ outfile.write("1998-01-01|1.0\n1999-01-01|2.0")
57
+
58
+ series = self.read_csv(path, sep="|", parse_dates=True)
59
+ check_series = Series(
60
+ {datetime(1998, 1, 1): 1.0, datetime(1999, 1, 1): 2.0}
61
+ )
62
+ tm.assert_series_equal(check_series, series)
63
+
64
+ series = self.read_csv(path, sep="|", parse_dates=False)
65
+ check_series = Series({"1998-01-01": 1.0, "1999-01-01": 2.0})
66
+ tm.assert_series_equal(check_series, series)
67
+
68
+ def test_to_csv(self, datetime_series):
69
+ with tm.ensure_clean() as path:
70
+ datetime_series.to_csv(path, header=False)
71
+
72
+ with open(path, newline=None, encoding="utf-8") as f:
73
+ lines = f.readlines()
74
+ assert lines[1] != "\n"
75
+
76
+ datetime_series.to_csv(path, index=False, header=False)
77
+ arr = np.loadtxt(path)
78
+ tm.assert_almost_equal(arr, datetime_series.values)
79
+
80
+ def test_to_csv_unicode_index(self):
81
+ buf = StringIO()
82
+ s = Series(["\u05d0", "d2"], index=["\u05d0", "\u05d1"])
83
+
84
+ s.to_csv(buf, encoding="UTF-8", header=False)
85
+ buf.seek(0)
86
+
87
+ s2 = self.read_csv(buf, index_col=0, encoding="UTF-8")
88
+ tm.assert_series_equal(s, s2)
89
+
90
+ def test_to_csv_float_format(self):
91
+ with tm.ensure_clean() as filename:
92
+ ser = Series([0.123456, 0.234567, 0.567567])
93
+ ser.to_csv(filename, float_format="%.2f", header=False)
94
+
95
+ rs = self.read_csv(filename)
96
+ xp = Series([0.12, 0.23, 0.57])
97
+ tm.assert_series_equal(rs, xp)
98
+
99
+ def test_to_csv_list_entries(self):
100
+ s = Series(["jack and jill", "jesse and frank"])
101
+
102
+ split = s.str.split(r"\s+and\s+")
103
+
104
+ buf = StringIO()
105
+ split.to_csv(buf, header=False)
106
+
107
+ def test_to_csv_path_is_none(self):
108
+ # GH 8215
109
+ # Series.to_csv() was returning None, inconsistent with
110
+ # DataFrame.to_csv() which returned string
111
+ s = Series([1, 2, 3])
112
+ csv_str = s.to_csv(path_or_buf=None, header=False)
113
+ assert isinstance(csv_str, str)
114
+
115
+ @pytest.mark.parametrize(
116
+ "s,encoding",
117
+ [
118
+ (
119
+ Series([0.123456, 0.234567, 0.567567], index=["A", "B", "C"], name="X"),
120
+ None,
121
+ ),
122
+ # GH 21241, 21118
123
+ (Series(["abc", "def", "ghi"], name="X"), "ascii"),
124
+ (Series(["123", "你好", "世界"], name="中文"), "gb2312"),
125
+ (
126
+ Series(["123", "Γειά σου", "Κόσμε"], name="Ελληνικά"), # noqa: RUF001
127
+ "cp737",
128
+ ),
129
+ ],
130
+ )
131
+ def test_to_csv_compression(self, s, encoding, compression):
132
+ with tm.ensure_clean() as filename:
133
+ s.to_csv(filename, compression=compression, encoding=encoding, header=True)
134
+ # test the round trip - to_csv -> read_csv
135
+ result = pd.read_csv(
136
+ filename,
137
+ compression=compression,
138
+ encoding=encoding,
139
+ index_col=0,
140
+ ).squeeze("columns")
141
+ tm.assert_series_equal(s, result)
142
+
143
+ # test the round trip using file handle - to_csv -> read_csv
144
+ with get_handle(
145
+ filename, "w", compression=compression, encoding=encoding
146
+ ) as handles:
147
+ s.to_csv(handles.handle, encoding=encoding, header=True)
148
+
149
+ result = pd.read_csv(
150
+ filename,
151
+ compression=compression,
152
+ encoding=encoding,
153
+ index_col=0,
154
+ ).squeeze("columns")
155
+ tm.assert_series_equal(s, result)
156
+
157
+ # explicitly ensure file was compressed
158
+ with tm.decompress_file(filename, compression) as fh:
159
+ text = fh.read().decode(encoding or "utf8")
160
+ assert s.name in text
161
+
162
+ with tm.decompress_file(filename, compression) as fh:
163
+ tm.assert_series_equal(
164
+ s,
165
+ pd.read_csv(fh, index_col=0, encoding=encoding).squeeze("columns"),
166
+ )
167
+
168
+ def test_to_csv_interval_index(self, using_infer_string):
169
+ # GH 28210
170
+ s = Series(["foo", "bar", "baz"], index=pd.interval_range(0, 3))
171
+
172
+ with tm.ensure_clean("__tmp_to_csv_interval_index__.csv") as path:
173
+ s.to_csv(path, header=False)
174
+ result = self.read_csv(path, index_col=0)
175
+
176
+ # can't roundtrip intervalindex via read_csv so check string repr (GH 23595)
177
+ expected = s
178
+ expected.index = expected.index.astype("str")
179
+ tm.assert_series_equal(result, expected)
shared/package-files/d6/d6456b0a1ce260e9f3f1ad9bac56981344dac7e82628a078434a75fe9aafc124/_convert_indices_from_coo_to_csr.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_convert_indices_from_coo_to_csr_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_convert_indices_from_coo_to_csr(Tensor self, int size, *, bool out_int32=False) -> Tensor
26
+ inline at::Tensor _convert_indices_from_coo_to_csr(const at::Tensor & self, int64_t size, bool out_int32=false) {
27
+ return at::_ops::_convert_indices_from_coo_to_csr::call(self, size, out_int32);
28
+ }
29
+
30
+ // aten::_convert_indices_from_coo_to_csr.out(Tensor self, int size, *, bool out_int32=False, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & _convert_indices_from_coo_to_csr_out(at::Tensor & out, const at::Tensor & self, int64_t size, bool out_int32=false) {
32
+ return at::_ops::_convert_indices_from_coo_to_csr_out::call(self, size, out_int32, out);
33
+ }
34
+ // aten::_convert_indices_from_coo_to_csr.out(Tensor self, int size, *, bool out_int32=False, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & _convert_indices_from_coo_to_csr_outf(const at::Tensor & self, int64_t size, bool out_int32, at::Tensor & out) {
36
+ return at::_ops::_convert_indices_from_coo_to_csr_out::call(self, size, out_int32, out);
37
+ }
38
+
39
+ }
shared/package-files/d6/d64be755da43107b26fa96414d885b356200b5c3335a80cf2642e921d789146a/_knn.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: The scikit-learn developers
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ from numbers import Integral
5
+
6
+ import numpy as np
7
+
8
+ from ..base import _fit_context
9
+ from ..metrics import pairwise_distances_chunked
10
+ from ..metrics.pairwise import _NAN_METRICS
11
+ from ..neighbors._base import _get_weights
12
+ from ..utils._mask import _get_mask
13
+ from ..utils._missing import is_scalar_nan
14
+ from ..utils._param_validation import Hidden, Interval, StrOptions
15
+ from ..utils.validation import (
16
+ FLOAT_DTYPES,
17
+ _check_feature_names_in,
18
+ check_is_fitted,
19
+ validate_data,
20
+ )
21
+ from ._base import _BaseImputer
22
+
23
+
24
+ class KNNImputer(_BaseImputer):
25
+ """Imputation for completing missing values using k-Nearest Neighbors.
26
+
27
+ Each sample's missing values are imputed using the mean value from
28
+ `n_neighbors` nearest neighbors found in the training set. Two samples are
29
+ close if the features that neither is missing are close.
30
+
31
+ Read more in the :ref:`User Guide <knnimpute>`.
32
+
33
+ .. versionadded:: 0.22
34
+
35
+ Parameters
36
+ ----------
37
+ missing_values : int, float, str, np.nan or None, default=np.nan
38
+ The placeholder for the missing values. All occurrences of
39
+ `missing_values` will be imputed. For pandas' dataframes with
40
+ nullable integer dtypes with missing values, `missing_values`
41
+ should be set to np.nan, since `pd.NA` will be converted to np.nan.
42
+
43
+ n_neighbors : int, default=5
44
+ Number of neighboring samples to use for imputation.
45
+
46
+ weights : {'uniform', 'distance'} or callable, default='uniform'
47
+ Weight function used in prediction. Possible values:
48
+
49
+ - 'uniform' : uniform weights. All points in each neighborhood are
50
+ weighted equally.
51
+ - 'distance' : weight points by the inverse of their distance.
52
+ in this case, closer neighbors of a query point will have a
53
+ greater influence than neighbors which are further away.
54
+ - callable : a user-defined function which accepts an
55
+ array of distances, and returns an array of the same shape
56
+ containing the weights.
57
+
58
+ metric : {'nan_euclidean'} or callable, default='nan_euclidean'
59
+ Distance metric for searching neighbors. Possible values:
60
+
61
+ - 'nan_euclidean'
62
+ - callable : a user-defined function which conforms to the definition
63
+ of ``func_metric(x, y, *, missing_values=np.nan)``. `x` and `y`
64
+ corresponds to a row (i.e. 1-D arrays) of `X` and `Y`, respectively.
65
+ The callable should returns a scalar distance value.
66
+
67
+ copy : bool, default=True
68
+ If True, a copy of X will be created. If False, imputation will
69
+ be done in-place whenever possible.
70
+
71
+ add_indicator : bool, default=False
72
+ If True, a :class:`MissingIndicator` transform will stack onto the
73
+ output of the imputer's transform. This allows a predictive estimator
74
+ to account for missingness despite imputation. If a feature has no
75
+ missing values at fit/train time, the feature won't appear on the
76
+ missing indicator even if there are missing values at transform/test
77
+ time.
78
+
79
+ keep_empty_features : bool, default=False
80
+ If True, features that consist exclusively of missing values when
81
+ `fit` is called are returned in results when `transform` is called.
82
+ The imputed value is always `0`.
83
+
84
+ .. versionadded:: 1.2
85
+
86
+ Attributes
87
+ ----------
88
+ indicator_ : :class:`~sklearn.impute.MissingIndicator`
89
+ Indicator used to add binary indicators for missing values.
90
+ ``None`` if add_indicator is False.
91
+
92
+ n_features_in_ : int
93
+ Number of features seen during :term:`fit`.
94
+
95
+ .. versionadded:: 0.24
96
+
97
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
98
+ Names of features seen during :term:`fit`. Defined only when `X`
99
+ has feature names that are all strings.
100
+
101
+ .. versionadded:: 1.0
102
+
103
+ See Also
104
+ --------
105
+ SimpleImputer : Univariate imputer for completing missing values
106
+ with simple strategies.
107
+ IterativeImputer : Multivariate imputer that estimates values to impute for
108
+ each feature with missing values from all the others.
109
+
110
+ References
111
+ ----------
112
+ * `Olga Troyanskaya, Michael Cantor, Gavin Sherlock, Pat Brown, Trevor
113
+ Hastie, Robert Tibshirani, David Botstein and Russ B. Altman, Missing
114
+ value estimation methods for DNA microarrays, BIOINFORMATICS Vol. 17
115
+ no. 6, 2001 Pages 520-525.
116
+ <https://academic.oup.com/bioinformatics/article/17/6/520/272365>`_
117
+
118
+ Examples
119
+ --------
120
+ >>> import numpy as np
121
+ >>> from sklearn.impute import KNNImputer
122
+ >>> X = [[1, 2, np.nan], [3, 4, 3], [np.nan, 6, 5], [8, 8, 7]]
123
+ >>> imputer = KNNImputer(n_neighbors=2)
124
+ >>> imputer.fit_transform(X)
125
+ array([[1. , 2. , 4. ],
126
+ [3. , 4. , 3. ],
127
+ [5.5, 6. , 5. ],
128
+ [8. , 8. , 7. ]])
129
+
130
+ For a more detailed example see
131
+ :ref:`sphx_glr_auto_examples_impute_plot_missing_values.py`.
132
+ """
133
+
134
+ _parameter_constraints: dict = {
135
+ **_BaseImputer._parameter_constraints,
136
+ "n_neighbors": [Interval(Integral, 1, None, closed="left")],
137
+ "weights": [StrOptions({"uniform", "distance"}), callable, Hidden(None)],
138
+ "metric": [StrOptions(set(_NAN_METRICS)), callable],
139
+ "copy": ["boolean"],
140
+ }
141
+
142
+ def __init__(
143
+ self,
144
+ *,
145
+ missing_values=np.nan,
146
+ n_neighbors=5,
147
+ weights="uniform",
148
+ metric="nan_euclidean",
149
+ copy=True,
150
+ add_indicator=False,
151
+ keep_empty_features=False,
152
+ ):
153
+ super().__init__(
154
+ missing_values=missing_values,
155
+ add_indicator=add_indicator,
156
+ keep_empty_features=keep_empty_features,
157
+ )
158
+ self.n_neighbors = n_neighbors
159
+ self.weights = weights
160
+ self.metric = metric
161
+ self.copy = copy
162
+
163
+ def _calc_impute(self, dist_pot_donors, n_neighbors, fit_X_col, mask_fit_X_col):
164
+ """Helper function to impute a single column.
165
+
166
+ Parameters
167
+ ----------
168
+ dist_pot_donors : ndarray of shape (n_receivers, n_potential_donors)
169
+ Distance matrix between the receivers and potential donors from
170
+ training set. There must be at least one non-nan distance between
171
+ a receiver and a potential donor.
172
+
173
+ n_neighbors : int
174
+ Number of neighbors to consider.
175
+
176
+ fit_X_col : ndarray of shape (n_potential_donors,)
177
+ Column of potential donors from training set.
178
+
179
+ mask_fit_X_col : ndarray of shape (n_potential_donors,)
180
+ Missing mask for fit_X_col.
181
+
182
+ Returns
183
+ -------
184
+ imputed_values: ndarray of shape (n_receivers,)
185
+ Imputed values for receiver.
186
+ """
187
+ # Get donors
188
+ donors_idx = np.argpartition(dist_pot_donors, n_neighbors - 1, axis=1)[
189
+ :, :n_neighbors
190
+ ]
191
+
192
+ # Get weight matrix from distance matrix
193
+ donors_dist = dist_pot_donors[
194
+ np.arange(donors_idx.shape[0])[:, None], donors_idx
195
+ ]
196
+
197
+ weight_matrix = _get_weights(donors_dist, self.weights)
198
+
199
+ # fill nans with zeros
200
+ if weight_matrix is not None:
201
+ weight_matrix[np.isnan(weight_matrix)] = 0.0
202
+ else:
203
+ weight_matrix = np.ones_like(donors_dist)
204
+ weight_matrix[np.isnan(donors_dist)] = 0.0
205
+
206
+ # Retrieve donor values and calculate kNN average
207
+ donors = fit_X_col.take(donors_idx)
208
+ donors_mask = mask_fit_X_col.take(donors_idx)
209
+ donors = np.ma.array(donors, mask=donors_mask)
210
+
211
+ return np.ma.average(donors, axis=1, weights=weight_matrix).data
212
+
213
+ @_fit_context(prefer_skip_nested_validation=True)
214
+ def fit(self, X, y=None):
215
+ """Fit the imputer on X.
216
+
217
+ Parameters
218
+ ----------
219
+ X : array-like shape of (n_samples, n_features)
220
+ Input data, where `n_samples` is the number of samples and
221
+ `n_features` is the number of features.
222
+
223
+ y : Ignored
224
+ Not used, present here for API consistency by convention.
225
+
226
+ Returns
227
+ -------
228
+ self : object
229
+ The fitted `KNNImputer` class instance.
230
+ """
231
+ # Check data integrity and calling arguments
232
+ if not is_scalar_nan(self.missing_values):
233
+ ensure_all_finite = True
234
+ else:
235
+ ensure_all_finite = "allow-nan"
236
+
237
+ X = validate_data(
238
+ self,
239
+ X,
240
+ accept_sparse=False,
241
+ dtype=FLOAT_DTYPES,
242
+ ensure_all_finite=ensure_all_finite,
243
+ copy=self.copy,
244
+ )
245
+
246
+ self._fit_X = X
247
+ self._mask_fit_X = _get_mask(self._fit_X, self.missing_values)
248
+ self._valid_mask = ~np.all(self._mask_fit_X, axis=0)
249
+
250
+ super()._fit_indicator(self._mask_fit_X)
251
+
252
+ return self
253
+
254
+ def transform(self, X):
255
+ """Impute all missing values in X.
256
+
257
+ Parameters
258
+ ----------
259
+ X : array-like of shape (n_samples, n_features)
260
+ The input data to complete.
261
+
262
+ Returns
263
+ -------
264
+ X : array-like of shape (n_samples, n_output_features)
265
+ The imputed dataset. `n_output_features` is the number of features
266
+ that is not always missing during `fit`.
267
+ """
268
+
269
+ check_is_fitted(self)
270
+ if not is_scalar_nan(self.missing_values):
271
+ ensure_all_finite = True
272
+ else:
273
+ ensure_all_finite = "allow-nan"
274
+ X = validate_data(
275
+ self,
276
+ X,
277
+ accept_sparse=False,
278
+ dtype=FLOAT_DTYPES,
279
+ force_writeable=True,
280
+ ensure_all_finite=ensure_all_finite,
281
+ copy=self.copy,
282
+ reset=False,
283
+ )
284
+
285
+ mask = _get_mask(X, self.missing_values)
286
+ mask_fit_X = self._mask_fit_X
287
+ valid_mask = self._valid_mask
288
+
289
+ X_indicator = super()._transform_indicator(mask)
290
+
291
+ # Removes columns where the training data is all nan
292
+ if not np.any(mask[:, valid_mask]):
293
+ # No missing values in X
294
+ if self.keep_empty_features:
295
+ Xc = X
296
+ Xc[:, ~valid_mask] = 0
297
+ else:
298
+ Xc = X[:, valid_mask]
299
+
300
+ # Even if there are no missing values in X, we still concatenate Xc
301
+ # with the missing value indicator matrix, X_indicator.
302
+ # This is to ensure that the output maintains consistency in terms
303
+ # of columns, regardless of whether missing values exist in X or not.
304
+ return super()._concatenate_indicator(Xc, X_indicator)
305
+
306
+ row_missing_idx = np.flatnonzero(mask[:, valid_mask].any(axis=1))
307
+
308
+ non_missing_fix_X = np.logical_not(mask_fit_X)
309
+
310
+ # Maps from indices from X to indices in dist matrix
311
+ dist_idx_map = np.zeros(X.shape[0], dtype=int)
312
+ dist_idx_map[row_missing_idx] = np.arange(row_missing_idx.shape[0])
313
+
314
+ def process_chunk(dist_chunk, start):
315
+ row_missing_chunk = row_missing_idx[start : start + len(dist_chunk)]
316
+
317
+ # Find and impute missing by column
318
+ for col in range(X.shape[1]):
319
+ if not valid_mask[col]:
320
+ # column was all missing during training
321
+ continue
322
+
323
+ col_mask = mask[row_missing_chunk, col]
324
+ if not np.any(col_mask):
325
+ # column has no missing values
326
+ continue
327
+
328
+ (potential_donors_idx,) = np.nonzero(non_missing_fix_X[:, col])
329
+
330
+ # receivers_idx are indices in X
331
+ receivers_idx = row_missing_chunk[np.flatnonzero(col_mask)]
332
+
333
+ # distances for samples that needed imputation for column
334
+ dist_subset = dist_chunk[dist_idx_map[receivers_idx] - start][
335
+ :, potential_donors_idx
336
+ ]
337
+
338
+ # receivers with all nan distances impute with mean
339
+ all_nan_dist_mask = np.isnan(dist_subset).all(axis=1)
340
+ all_nan_receivers_idx = receivers_idx[all_nan_dist_mask]
341
+
342
+ if all_nan_receivers_idx.size:
343
+ col_mean = np.ma.array(
344
+ self._fit_X[:, col], mask=mask_fit_X[:, col]
345
+ ).mean()
346
+ X[all_nan_receivers_idx, col] = col_mean
347
+
348
+ if len(all_nan_receivers_idx) == len(receivers_idx):
349
+ # all receivers imputed with mean
350
+ continue
351
+
352
+ # receivers with at least one defined distance
353
+ receivers_idx = receivers_idx[~all_nan_dist_mask]
354
+ dist_subset = dist_chunk[dist_idx_map[receivers_idx] - start][
355
+ :, potential_donors_idx
356
+ ]
357
+
358
+ n_neighbors = min(self.n_neighbors, len(potential_donors_idx))
359
+ value = self._calc_impute(
360
+ dist_subset,
361
+ n_neighbors,
362
+ self._fit_X[potential_donors_idx, col],
363
+ mask_fit_X[potential_donors_idx, col],
364
+ )
365
+ X[receivers_idx, col] = value
366
+
367
+ # process in fixed-memory chunks
368
+ gen = pairwise_distances_chunked(
369
+ X[row_missing_idx, :],
370
+ self._fit_X,
371
+ metric=self.metric,
372
+ missing_values=self.missing_values,
373
+ ensure_all_finite=ensure_all_finite,
374
+ reduce_func=process_chunk,
375
+ )
376
+ for chunk in gen:
377
+ # process_chunk modifies X in place. No return value.
378
+ pass
379
+
380
+ if self.keep_empty_features:
381
+ Xc = X
382
+ Xc[:, ~valid_mask] = 0
383
+ else:
384
+ Xc = X[:, valid_mask]
385
+
386
+ return super()._concatenate_indicator(Xc, X_indicator)
387
+
388
+ def get_feature_names_out(self, input_features=None):
389
+ """Get output feature names for transformation.
390
+
391
+ Parameters
392
+ ----------
393
+ input_features : array-like of str or None, default=None
394
+ Input features.
395
+
396
+ - If `input_features` is `None`, then `feature_names_in_` is
397
+ used as feature names in. If `feature_names_in_` is not defined,
398
+ then the following input feature names are generated:
399
+ `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
400
+ - If `input_features` is an array-like, then `input_features` must
401
+ match `feature_names_in_` if `feature_names_in_` is defined.
402
+
403
+ Returns
404
+ -------
405
+ feature_names_out : ndarray of str objects
406
+ Transformed feature names.
407
+ """
408
+ check_is_fitted(self, "n_features_in_")
409
+ input_features = _check_feature_names_in(self, input_features)
410
+ names = input_features[self._valid_mask]
411
+ return self._concatenate_indicator_feature_names_out(names, input_features)
shared/package-files/d6/d64eaf3a093a6c3eff4219a0750ce20823d67b80838ea1bcfe005b369ca971a9/narrow_copy_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API narrow_copy {
18
+ using schema = at::Tensor (const at::Tensor &, int64_t, c10::SymInt, c10::SymInt);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::narrow_copy")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "narrow_copy(Tensor self, int dim, SymInt start, SymInt length) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, int64_t dim, c10::SymInt start, c10::SymInt length);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, c10::SymInt start, c10::SymInt length);
26
+ };
27
+
28
+ struct TORCH_API narrow_copy_out {
29
+ using schema = at::Tensor & (const at::Tensor &, int64_t, c10::SymInt, c10::SymInt, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::narrow_copy")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "narrow_copy.out(Tensor self, int dim, SymInt start, SymInt length, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, int64_t dim, c10::SymInt start, c10::SymInt length, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, c10::SymInt start, c10::SymInt length, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/d6/d654e7dbb66735047c936f6caaf1089e79d23db7e9f4eeb9642cba995c00017d/att620-103k-w ADDED
Binary file (1.71 kB). View file
 
shared/package-files/d6/d658a0be19c1975e06e2be07afd0ff1b8baccfcd44ce0c702039256393f58410/ros.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation of Regression on Order Statistics for imputing left-
3
+ censored (non-detect data)
4
+
5
+ Method described in *Nondetects and Data Analysis* by Dennis R.
6
+ Helsel (John Wiley, 2005) to estimate the left-censored (non-detect)
7
+ values of a dataset.
8
+
9
+ Author: Paul M. Hobson
10
+ Company: Geosyntec Consultants (Portland, OR)
11
+ Date: 2016-06-14
12
+
13
+ """
14
+
15
+ import warnings
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+ from scipy import stats
20
+
21
+ from statsmodels.tools.sm_exceptions import SpecificationWarning
22
+
23
+
24
+ def _ros_sort(df, observations, censorship, warn=False):
25
+ """
26
+ Prepare a dataframe for ROS
27
+
28
+ It sorts ascending with
29
+ left-censored observations first. Censored observations larger than
30
+ the maximum uncensored observations are removed from the dataframe.
31
+
32
+ Parameters
33
+ ----------
34
+ df : DataFrame
35
+ The data to be sorted.
36
+
37
+ observations : str
38
+ Name of the column in the dataframe that contains observed
39
+ values. Censored values should be set to the detection (upper)
40
+ limit.
41
+
42
+ censorship : str
43
+ Name of the column in the dataframe that indicates that a
44
+ observation is left-censored. (i.e., True -> censored,
45
+ False -> uncensored)
46
+
47
+ warn : bool, optional
48
+ Whether to warn when censored observations larger than the
49
+ maximum uncensored observation are dropped.
50
+
51
+ Returns
52
+ -------
53
+ sorted_df : DataFrame
54
+ The sorted dataframe with all columns dropped except the
55
+ observation and censorship columns.
56
+ """
57
+
58
+ # separate uncensored data from censored data
59
+ censored = df[df[censorship]].sort_values(observations, axis=0)
60
+ uncensored = df[~df[censorship]].sort_values(observations, axis=0)
61
+
62
+ if censored[observations].max() > uncensored[observations].max():
63
+ censored = censored[censored[observations] <= uncensored[observations].max()]
64
+
65
+ if warn:
66
+ msg = (
67
+ "Dropping censored observations greater than "
68
+ "the max uncensored observation."
69
+ )
70
+ warnings.warn(msg, SpecificationWarning, stacklevel=2)
71
+
72
+ combined = pd.concat([censored, uncensored], axis=0)
73
+ return combined[[observations, censorship]].reset_index(drop=True)
74
+
75
+
76
+ def cohn_numbers(df, observations, censorship):
77
+ r"""
78
+ Compute the Cohn numbers for the detection limits in the dataset
79
+
80
+ The Cohn Numbers are:
81
+
82
+ - :math:`A_j =` the number of uncensored obs above the jth
83
+ threshold.
84
+ - :math:`B_j =` the number of observations (cen & uncen) below
85
+ the jth threshold.
86
+ - :math:`C_j =` the number of censored observations at the jth
87
+ threshold.
88
+ - :math:`\mathrm{PE}_j =` the probability of exceeding the jth
89
+ threshold
90
+ - :math:`\mathrm{DL}_j =` the unique, sorted detection limits
91
+ - :math:`\mathrm{DL}_{j+1} = \mathrm{DL}_j` shifted down a
92
+ single index (row)
93
+
94
+ Parameters
95
+ ----------
96
+ df : DataFrame
97
+ The data used to compute the Cohn numbers.
98
+
99
+ observations : str
100
+ Name of the column in the dataframe that contains observed
101
+ values. Censored values should be set to the detection (upper)
102
+ limit.
103
+
104
+ censorship : str
105
+ Name of the column in the dataframe that indicates that a
106
+ observation is left-censored. (i.e., True -> censored,
107
+ False -> uncensored)
108
+
109
+ Returns
110
+ -------
111
+ cohn : DataFrame
112
+ The dataframe of Cohn numbers.
113
+ """
114
+
115
+ def nuncen_above(row):
116
+ """A, the number of uncensored obs above the given threshold"""
117
+
118
+ # index of observations above the lower_dl DL
119
+ above = df[observations] >= row["lower_dl"]
120
+
121
+ # index of observations below the upper_dl DL
122
+ below = df[observations] < row["upper_dl"]
123
+
124
+ # index of non-detect observations
125
+ detect = ~df[censorship]
126
+
127
+ # return the number of observations where all conditions are True
128
+ return df[above & below & detect].shape[0]
129
+
130
+ def nobs_below(row):
131
+ """B, the number of observations (cen and uncen) below the given threshold"""
132
+
133
+ # index of data less than the lower_dl DL
134
+ less_than = df[observations] < row["lower_dl"]
135
+
136
+ # index of data less than or equal to the lower_dl DL
137
+ less_thanequal = df[observations] <= row["lower_dl"]
138
+
139
+ # index of detects, non-detects
140
+ uncensored = ~df[censorship]
141
+ censored = df[censorship]
142
+
143
+ # number observations less than or equal to lower_dl DL and non-detect
144
+ LTE_censored = df[less_thanequal & censored].shape[0]
145
+
146
+ # number of observations less than lower_dl DL and detected
147
+ LT_uncensored = df[less_than & uncensored].shape[0]
148
+
149
+ # return the sum
150
+ return LTE_censored + LT_uncensored
151
+
152
+ def ncen_equal(row):
153
+ """C, the number of censored observations at the given threshold"""
154
+
155
+ censored_index = df[censorship]
156
+ censored_data = df[observations][censored_index]
157
+ censored_below = censored_data == row["lower_dl"]
158
+ return censored_below.sum()
159
+
160
+ def set_upper_limit(cohn):
161
+ """Set the upper_dl DL for each row of the Cohn dataframe"""
162
+ if cohn.shape[0] > 1:
163
+ return cohn["lower_dl"].shift(-1).fillna(value=np.inf)
164
+ else:
165
+ return [np.inf]
166
+
167
+ def compute_PE(A, B):
168
+ """Compute the probability of exceedance for each row of the Cohn dataframe"""
169
+ N = len(A)
170
+ PE = np.empty(N, dtype="float64")
171
+ PE[-1] = 0.0
172
+ for j in range(N - 2, -1, -1):
173
+ PE[j] = PE[j + 1] + (1 - PE[j + 1]) * A[j] / (A[j] + B[j])
174
+
175
+ return PE
176
+
177
+ # unique, sorted detection limts
178
+ censored_data = df[censorship]
179
+ DLs = pd.unique(df.loc[censored_data, observations])
180
+ DLs.sort()
181
+
182
+ # if there is a observations smaller than the minimum detection limit,
183
+ # add that value to the array
184
+ if DLs.shape[0] > 0:
185
+ if df[observations].min() < DLs.min():
186
+ DLs = np.hstack([df[observations].min(), DLs])
187
+
188
+ # create a dataframe
189
+ # (editted for pandas 0.14 compatibility; see commit 63f162e
190
+ # when `pipe` and `assign` are available)
191
+ cohn = pd.DataFrame(DLs, columns=["lower_dl"])
192
+ cohn.loc[:, "upper_dl"] = set_upper_limit(cohn)
193
+ cohn.loc[:, "nuncen_above"] = cohn.apply(nuncen_above, axis=1)
194
+ cohn.loc[:, "nobs_below"] = cohn.apply(nobs_below, axis=1)
195
+ cohn.loc[:, "ncen_equal"] = cohn.apply(ncen_equal, axis=1)
196
+ cohn = cohn.reindex(range(DLs.shape[0] + 1))
197
+ cohn.loc[:, "prob_exceedance"] = compute_PE(
198
+ cohn["nuncen_above"], cohn["nobs_below"]
199
+ )
200
+
201
+ else:
202
+ dl_cols = [
203
+ "lower_dl",
204
+ "upper_dl",
205
+ "nuncen_above",
206
+ "nobs_below",
207
+ "ncen_equal",
208
+ "prob_exceedance",
209
+ ]
210
+ cohn = pd.DataFrame(np.empty((0, len(dl_cols))), columns=dl_cols)
211
+
212
+ return cohn
213
+
214
+
215
+ def _detection_limit_index(obs, cohn):
216
+ """
217
+ Locates the corresponding detection limit for each observation.
218
+
219
+ Basically, creates an array of indices for the detection limits
220
+ (Cohn numbers) corresponding to each data point.
221
+
222
+ Parameters
223
+ ----------
224
+ obs : float
225
+ A single observation from the larger dataset.
226
+
227
+ cohn : DataFrame
228
+ DataFrame of Cohn numbers.
229
+
230
+ Returns
231
+ -------
232
+ det_limit_index : int
233
+ The index of the corresponding detection limit in `cohn`
234
+
235
+ See Also
236
+ --------
237
+ cohn_numbers
238
+ """
239
+
240
+ if cohn.shape[0] > 0:
241
+ (index,) = np.where(cohn["lower_dl"] <= obs)
242
+ det_limit_index = index[-1]
243
+ else:
244
+ det_limit_index = 0
245
+
246
+ return det_limit_index
247
+
248
+
249
+ def _ros_group_rank(df, dl_idx, censorship):
250
+ """
251
+ Ranks each observation within the data groups.
252
+
253
+ In this case, the groups are defined by the record's detection
254
+ limit index and censorship status.
255
+
256
+ Parameters
257
+ ----------
258
+ df : DataFrame
259
+
260
+ dl_idx : str
261
+ Name of the column in the dataframe the index of the
262
+ observations' corresponding detection limit in the `cohn`
263
+ dataframe.
264
+
265
+ censorship : str
266
+ Name of the column in the dataframe that indicates that a
267
+ observation is left-censored. (i.e., True -> censored,
268
+ False -> uncensored)
269
+
270
+ Returns
271
+ -------
272
+ ranks : Series
273
+ Series of ranks for the dataset.
274
+ """
275
+
276
+ # (editted for pandas 0.14 compatibility; see commit 63f162e
277
+ # when `pipe` and `assign` are available)
278
+ ranks = df.copy()
279
+ ranks.loc[:, "rank"] = 1
280
+ ranks = ranks.groupby(by=[dl_idx, censorship])["rank"].transform(
281
+ lambda g: g.cumsum()
282
+ )
283
+ return ranks
284
+
285
+
286
+ def _ros_plot_pos(row, censorship, cohn):
287
+ """
288
+ ROS-specific plotting positions.
289
+
290
+ Computes the plotting position for an observation based on its rank,
291
+ censorship status, and detection limit index.
292
+
293
+ Parameters
294
+ ----------
295
+ row : Series or dict
296
+ Full observation (row) from a censored dataset. Requires a
297
+ 'rank', 'det_limit_index', and `censorship` column.
298
+
299
+ censorship : str
300
+ Name of the column in the dataframe that indicates that a
301
+ observation is left-censored. (i.e., True -> censored,
302
+ False -> uncensored)
303
+
304
+ cohn : DataFrame
305
+ DataFrame of Cohn numbers.
306
+
307
+ Returns
308
+ -------
309
+ plotting_position : float
310
+
311
+ See Also
312
+ --------
313
+ cohn_numbers
314
+ """
315
+
316
+ DL_index = row["det_limit_index"]
317
+ rank = row["rank"]
318
+ censored = row[censorship]
319
+
320
+ dl_1 = cohn.iloc[DL_index]
321
+ dl_2 = cohn.iloc[DL_index + 1]
322
+ if censored:
323
+ return (1 - dl_1["prob_exceedance"]) * rank / (dl_1["ncen_equal"] + 1)
324
+ else:
325
+ return (1 - dl_1["prob_exceedance"]) + (
326
+ dl_1["prob_exceedance"] - dl_2["prob_exceedance"]
327
+ ) * rank / (dl_1["nuncen_above"] + 1)
328
+
329
+
330
+ def _norm_plot_pos(observations):
331
+ """
332
+ Computes standard normal (Gaussian) plotting positions using scipy.
333
+
334
+ Parameters
335
+ ----------
336
+ observations : array_like
337
+ Sequence of observed quantities.
338
+
339
+ Returns
340
+ -------
341
+ plotting_position : ndarray
342
+ Array of standard normal plotting positions.
343
+ """
344
+ ppos, sorted_res = stats.probplot(observations, fit=False)
345
+ return stats.norm.cdf(ppos)
346
+
347
+
348
+ def plotting_positions(df, censorship, cohn):
349
+ """
350
+ Compute the plotting positions for the observations.
351
+
352
+ The ROS-specific plotting positions are based on the observations'
353
+ rank, censorship status, and corresponding detection limit.
354
+
355
+ Parameters
356
+ ----------
357
+ df : DataFrame
358
+
359
+ censorship : str
360
+ Name of the column in the dataframe that indicates that a
361
+ observation is left-censored. (i.e., True -> censored,
362
+ False -> uncensored)
363
+
364
+ cohn : DataFrame
365
+ DataFrame of Cohn numbers.
366
+
367
+ Returns
368
+ -------
369
+ plotting_position : Series
370
+ Series of plotting positions.
371
+
372
+ See Also
373
+ --------
374
+ cohn_numbers
375
+ """
376
+
377
+ plot_pos = df.apply(lambda r: _ros_plot_pos(r, censorship, cohn), axis=1)
378
+
379
+ # correctly sort the plotting positions of the ND data:
380
+ ND_plotpos = plot_pos[df[censorship]]
381
+ ND_plotpos_arr = np.sort(np.array(ND_plotpos))
382
+ plot_pos.loc[df[censorship].index[df[censorship]]] = ND_plotpos_arr
383
+
384
+ return plot_pos
385
+
386
+
387
+ def _impute(df, observations, censorship, transform_in, transform_out):
388
+ """
389
+ Execute the basic regression on order stat (ROS) procedure
390
+
391
+ Uses ROS to impute censored from the best-fit line of a
392
+ probability plot of the uncensored values.
393
+
394
+ Parameters
395
+ ----------
396
+ df : DataFrame
397
+ The data to be imputed. Must contain a "Zprelim" column of
398
+ normal scores used to fit the regression line.
399
+ observations : str
400
+ Name of the column in the dataframe that contains observed
401
+ values. Censored values should be set to the detection (upper)
402
+ limit.
403
+ censorship : str
404
+ Name of the column in the dataframe that indicates that a
405
+ observation is left-censored. (i.e., True -> censored,
406
+ False -> uncensored)
407
+ transform_in, transform_out : callable
408
+ Transformations to be applied to the data prior to fitting
409
+ the line and after estimated values from that line. Typically,
410
+ `np.log` and `np.exp` are used, respectively.
411
+
412
+ Returns
413
+ -------
414
+ estimated : DataFrame
415
+ A new dataframe with two new columns: "estimated" and "final".
416
+ The "estimated" column contains of the values inferred from the
417
+ best-fit line. The "final" column contains the estimated values
418
+ only where the original observations were censored, and the original
419
+ observations everywhere else.
420
+ """
421
+
422
+ # detect/non-detect selectors
423
+ uncensored_mask = ~df[censorship]
424
+ censored_mask = df[censorship]
425
+
426
+ # fit a line to the logs of the detected data
427
+ fit_params = stats.linregress(
428
+ df["Zprelim"][uncensored_mask], transform_in(df[observations][uncensored_mask])
429
+ )
430
+
431
+ # pull out the slope and intercept for use later
432
+ slope, intercept = fit_params[:2]
433
+
434
+ # model the data based on the best-fit curve
435
+ # (editted for pandas 0.14 compatibility; see commit 63f162e
436
+ # when `pipe` and `assign` are available)
437
+ df.loc[:, "estimated"] = transform_out(
438
+ slope * df["Zprelim"][censored_mask] + intercept
439
+ )
440
+ df.loc[:, "final"] = np.where(df[censorship], df["estimated"], df[observations])
441
+
442
+ return df
443
+
444
+
445
+ def _do_ros(df, observations, censorship, transform_in, transform_out):
446
+ """
447
+ DataFrame-centric function to impute censored values with ROS
448
+
449
+ Prepares a dataframe for, and then estimates the values of a censored
450
+ dataset using Regression on Order Statistics.
451
+
452
+ Parameters
453
+ ----------
454
+ df : DataFrame
455
+ The data to be imputed.
456
+
457
+ observations : str
458
+ Name of the column in the dataframe that contains observed
459
+ values. Censored values should be set to the detection (upper)
460
+ limit.
461
+
462
+ censorship : str
463
+ Name of the column in the dataframe that indicates that a
464
+ observation is left-censored. (i.e., True -> censored,
465
+ False -> uncensored)
466
+
467
+ transform_in, transform_out : callable
468
+ Transformations to be applied to the data prior to fitting
469
+ the line and after estimated values from that line. Typically,
470
+ `np.log` and `np.exp` are used, respectively.
471
+
472
+ Returns
473
+ -------
474
+ estimated : DataFrame
475
+ A new dataframe with two new columns: "estimated" and "final".
476
+ The "estimated" column contains of the values inferred from the
477
+ best-fit line. The "final" column contains the estimated values
478
+ only where the original observations were censored, and the original
479
+ observations everywhere else.
480
+ """
481
+
482
+ # compute the Cohn numbers
483
+ cohn = cohn_numbers(df, observations=observations, censorship=censorship)
484
+
485
+ # (editted for pandas 0.14 compatibility; see commit 63f162e
486
+ # when `pipe` and `assign` are available)
487
+ modeled = _ros_sort(df, observations=observations, censorship=censorship)
488
+ modeled.loc[:, "det_limit_index"] = modeled[observations].apply(
489
+ _detection_limit_index, args=(cohn,)
490
+ )
491
+ modeled.loc[:, "rank"] = _ros_group_rank(modeled, "det_limit_index", censorship)
492
+ modeled.loc[:, "plot_pos"] = plotting_positions(modeled, censorship, cohn)
493
+ modeled.loc[:, "Zprelim"] = stats.norm.ppf(modeled["plot_pos"])
494
+
495
+ return _impute(modeled, observations, censorship, transform_in, transform_out)
496
+
497
+
498
+ def impute_ros(
499
+ observations,
500
+ censorship,
501
+ df=None,
502
+ min_uncensored=2,
503
+ max_fraction_censored=0.8,
504
+ substitution_fraction=0.5,
505
+ transform_in=np.log,
506
+ transform_out=np.exp,
507
+ as_array=True,
508
+ ):
509
+ """
510
+ Impute censored dataset using Regression on Order Statistics (ROS)
511
+
512
+ Method described in *Nondetects and Data Analysis* by Dennis R.
513
+ Helsel (John Wiley, 2005) to estimate the left-censored (non-detect)
514
+ values of a dataset. When there is insufficient non-censored data,
515
+ simple substitution is used.
516
+
517
+ Parameters
518
+ ----------
519
+ observations : str or array_like
520
+ Label of the column or the float array of censored observations
521
+
522
+ censorship : str or array_like
523
+ Label of the column or the bool array of the censorship
524
+ status of the observations.
525
+
526
+ * True if censored,
527
+ * False if uncensored
528
+
529
+ df : DataFrame, optional
530
+ If `observations` and `censorship` are labels, this is the
531
+ DataFrame that contains those columns.
532
+
533
+ min_uncensored : int, optional
534
+ The minimum number of uncensored values required before ROS
535
+ can be used to impute the censored observations. When this
536
+ criterion is not met, simple substitution is used instead.
537
+ Default is 2.
538
+
539
+ max_fraction_censored : float, optional
540
+ The maximum fraction of censored data below which ROS can be
541
+ used to impute the censored observations. When this fraction is
542
+ exceeded, simple substituion is used instead. Default is 0.8.
543
+
544
+ substitution_fraction : float, optional
545
+ The fraction of the detection limit to be used during simple
546
+ substitution of the censored values. Default is 0.5.
547
+
548
+ transform_in : callable, optional
549
+ Transformation to be applied to the values prior to fitting a
550
+ line to the plotting positions vs. uncensored values. Default
551
+ is ``np.log``.
552
+
553
+ transform_out : callable, optional
554
+ Transformation to be applied to the imputed censored values
555
+ estimated from the previously computed best-fit line. Default
556
+ is ``np.exp``.
557
+
558
+ as_array : bool, optional
559
+ When True, a numpy array of the imputed observations is
560
+ returned. Otherwise, a modified copy of the original dataframe
561
+ with all of the intermediate calculations is returned. Default
562
+ is True.
563
+
564
+ Returns
565
+ -------
566
+ imputed : ndarray or DataFrame
567
+ The final observations where the censored values have either been
568
+ imputed through ROS or substituted as a fraction of the
569
+ detection limit.
570
+
571
+ Notes
572
+ -----
573
+ This function requires pandas 0.14 or more recent.
574
+ """
575
+
576
+ # process arrays into a dataframe, if necessary
577
+ if df is None:
578
+ df = pd.DataFrame({"obs": observations, "cen": censorship})
579
+ observations = "obs"
580
+ censorship = "cen"
581
+
582
+ # basic counts/metrics of the dataset
583
+ N_observations = df.shape[0]
584
+ N_censored = df[censorship].astype(int).sum()
585
+ N_uncensored = N_observations - N_censored
586
+ fraction_censored = N_censored / N_observations
587
+
588
+ # add plotting positions if there are no censored values
589
+ # (editted for pandas 0.14 compatibility; see commit 63f162e
590
+ # when `pipe` and `assign` are available)
591
+ if N_censored == 0:
592
+ output = df[[observations, censorship]].copy()
593
+ output.loc[:, "final"] = df[observations]
594
+
595
+ # substitute w/ fraction of the DLs if there's insufficient
596
+ # uncensored data
597
+ # (editted for pandas 0.14 compatibility; see commit 63f162e
598
+ # when `pipe` and `assign` are available)
599
+ elif (N_uncensored < min_uncensored) or (fraction_censored > max_fraction_censored):
600
+ output = df[[observations, censorship]].copy()
601
+ output.loc[:, "final"] = df[observations]
602
+ output.loc[df[censorship], "final"] *= substitution_fraction
603
+
604
+ # normal ROS stuff
605
+ else:
606
+ output = _do_ros(df, observations, censorship, transform_in, transform_out)
607
+
608
+ # convert to an array if necessary
609
+ if as_array:
610
+ output = output["final"].values
611
+
612
+ return output
shared/package-files/d6/d65c2a89d2a4e5cdd32a87a7db71b6f5fd65c8bd74fb4774f7dc35b254593873/cudnn_affine_grid_generator_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & cudnn_affine_grid_generator_out(const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W, at::Tensor & out);
20
+ TORCH_API at::Tensor cudnn_affine_grid_generator_forward(const at::Tensor & theta, int64_t N, int64_t C, int64_t H, int64_t W);
21
+ } // namespace native
22
+ } // namespace at
shared/package-files/d6/d668b1518304dba5f75c2f51d689eb9db1fdd5be52f7828fa6755945cd19d020/cyaml.pyi ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from _typeshed import SupportsRead
2
+ from typing import IO, Any, Mapping, Optional, Sequence, Text, Union
3
+
4
+ from yaml.constructor import BaseConstructor, Constructor, SafeConstructor
5
+ from yaml.representer import BaseRepresenter, Representer, SafeRepresenter
6
+ from yaml.resolver import BaseResolver, Resolver
7
+ from yaml.serializer import Serializer
8
+
9
+ _Readable = SupportsRead[Union[Text, bytes]]
10
+
11
+ class CParser:
12
+ def __init__(self, stream: Union[str, bytes, _Readable]) -> None: ...
13
+
14
+ class CBaseLoader(CParser, BaseConstructor, BaseResolver):
15
+ def __init__(self, stream: Union[str, bytes, _Readable]) -> None: ...
16
+
17
+ class CLoader(CParser, SafeConstructor, Resolver):
18
+ def __init__(self, stream: Union[str, bytes, _Readable]) -> None: ...
19
+
20
+ class CSafeLoader(CParser, SafeConstructor, Resolver):
21
+ def __init__(self, stream: Union[str, bytes, _Readable]) -> None: ...
22
+
23
+ class CDangerLoader(CParser, Constructor, Resolver): ... # undocumented
24
+
25
+ class CEmitter(object):
26
+ def __init__(
27
+ self,
28
+ stream: IO[Any],
29
+ canonical: Optional[Any] = ...,
30
+ indent: Optional[int] = ...,
31
+ width: Optional[int] = ...,
32
+ allow_unicode: Optional[Any] = ...,
33
+ line_break: Optional[str] = ...,
34
+ encoding: Optional[Text] = ...,
35
+ explicit_start: Optional[Any] = ...,
36
+ explicit_end: Optional[Any] = ...,
37
+ version: Optional[Sequence[int]] = ...,
38
+ tags: Optional[Mapping[Text, Text]] = ...,
39
+ ) -> None: ...
40
+
41
+ class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver):
42
+ def __init__(
43
+ self,
44
+ stream: IO[Any],
45
+ default_style: Optional[str] = ...,
46
+ default_flow_style: Optional[bool] = ...,
47
+ canonical: Optional[Any] = ...,
48
+ indent: Optional[int] = ...,
49
+ width: Optional[int] = ...,
50
+ allow_unicode: Optional[Any] = ...,
51
+ line_break: Optional[str] = ...,
52
+ encoding: Optional[Text] = ...,
53
+ explicit_start: Optional[Any] = ...,
54
+ explicit_end: Optional[Any] = ...,
55
+ version: Optional[Sequence[int]] = ...,
56
+ tags: Optional[Mapping[Text, Text]] = ...,
57
+ ) -> None: ...
58
+
59
+ class CDumper(CEmitter, SafeRepresenter, Resolver): ...
60
+
61
+ CSafeDumper = CDumper
62
+
63
+ class CDangerDumper(CEmitter, Serializer, Representer, Resolver): ... # undocumented
shared/package-files/d6/d66ab1c4b5c4492ce5888976e2e0a29c01707a0b8bf213d2d3aa4a3d27fab3f2/slow_conv3d_forward_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API slow_conv3d_forward_output {
18
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, const c10::optional<at::Tensor> &, c10::SymIntArrayRef, c10::SymIntArrayRef, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::slow_conv3d_forward")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "output")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "slow_conv3d_forward.output(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, *, Tensor(a!) output) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & output);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, at::Tensor & output);
26
+ };
27
+
28
+ struct TORCH_API slow_conv3d_forward {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, const c10::optional<at::Tensor> &, c10::SymIntArrayRef, c10::SymIntArrayRef);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::slow_conv3d_forward")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "slow_conv3d_forward(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/d6/d66fbf2ce0769a5dfcaaf71fd504355ddd80af0c263fb4695d1dded0feed0be7/_testing.py ADDED
@@ -0,0 +1,1454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Testing utilities."""
2
+
3
+ # Authors: The scikit-learn developers
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+
6
+ import atexit
7
+ import contextlib
8
+ import functools
9
+ import importlib
10
+ import inspect
11
+ import os
12
+ import os.path as op
13
+ import re
14
+ import shutil
15
+ import sys
16
+ import tempfile
17
+ import textwrap
18
+ import unittest
19
+ import warnings
20
+ from collections import defaultdict, namedtuple
21
+ from collections.abc import Iterable
22
+ from dataclasses import dataclass
23
+ from difflib import context_diff
24
+ from functools import wraps
25
+ from inspect import signature
26
+ from itertools import chain, groupby
27
+ from subprocess import STDOUT, CalledProcessError, TimeoutExpired, check_output
28
+
29
+ import joblib
30
+ import numpy as np
31
+ import scipy as sp
32
+ from numpy.testing import assert_allclose as np_assert_allclose
33
+ from numpy.testing import (
34
+ assert_almost_equal,
35
+ assert_array_almost_equal,
36
+ assert_array_equal,
37
+ assert_array_less,
38
+ )
39
+
40
+ import sklearn
41
+ from sklearn.utils import (
42
+ ClassifierTags,
43
+ RegressorTags,
44
+ Tags,
45
+ TargetTags,
46
+ TransformerTags,
47
+ )
48
+ from sklearn.utils._array_api import _check_array_api_dispatch
49
+ from sklearn.utils.fixes import (
50
+ _IS_32BIT,
51
+ VisibleDeprecationWarning,
52
+ _in_unstable_openblas_configuration,
53
+ )
54
+ from sklearn.utils.multiclass import check_classification_targets
55
+ from sklearn.utils.validation import (
56
+ check_array,
57
+ check_is_fitted,
58
+ check_X_y,
59
+ )
60
+
61
+ __all__ = [
62
+ "SkipTest",
63
+ "assert_allclose",
64
+ "assert_almost_equal",
65
+ "assert_array_almost_equal",
66
+ "assert_array_equal",
67
+ "assert_array_less",
68
+ "assert_run_python_script_without_output",
69
+ ]
70
+
71
+ SkipTest = unittest.case.SkipTest
72
+
73
+
74
+ def ignore_warnings(obj=None, category=Warning):
75
+ """Context manager and decorator to ignore warnings.
76
+
77
+ Note: Using this (in both variants) will clear all warnings
78
+ from all python modules loaded. In case you need to test
79
+ cross-module-warning-logging, this is not your tool of choice.
80
+
81
+ Parameters
82
+ ----------
83
+ obj : callable, default=None
84
+ callable where you want to ignore the warnings.
85
+ category : warning class, default=Warning
86
+ The category to filter. If Warning, all categories will be muted.
87
+
88
+ Examples
89
+ --------
90
+ >>> import warnings
91
+ >>> from sklearn.utils._testing import ignore_warnings
92
+ >>> with ignore_warnings():
93
+ ... warnings.warn('buhuhuhu')
94
+
95
+ >>> def nasty_warn():
96
+ ... warnings.warn('buhuhuhu')
97
+ ... print(42)
98
+
99
+ >>> ignore_warnings(nasty_warn)()
100
+ 42
101
+ """
102
+ if isinstance(obj, type) and issubclass(obj, Warning):
103
+ # Avoid common pitfall of passing category as the first positional
104
+ # argument which result in the test not being run
105
+ warning_name = obj.__name__
106
+ raise ValueError(
107
+ "'obj' should be a callable where you want to ignore warnings. "
108
+ "You passed a warning class instead: 'obj={warning_name}'. "
109
+ "If you want to pass a warning class to ignore_warnings, "
110
+ "you should use 'category={warning_name}'".format(warning_name=warning_name)
111
+ )
112
+ elif callable(obj):
113
+ return _IgnoreWarnings(category=category)(obj)
114
+ else:
115
+ return _IgnoreWarnings(category=category)
116
+
117
+
118
+ class _IgnoreWarnings:
119
+ """Improved and simplified Python warnings context manager and decorator.
120
+
121
+ This class allows the user to ignore the warnings raised by a function.
122
+ Copied from Python 2.7.5 and modified as required.
123
+
124
+ Parameters
125
+ ----------
126
+ category : tuple of warning class, default=Warning
127
+ The category to filter. By default, all the categories will be muted.
128
+
129
+ """
130
+
131
+ def __init__(self, category):
132
+ self._record = True
133
+ self._module = sys.modules["warnings"]
134
+ self._entered = False
135
+ self.log = []
136
+ self.category = category
137
+
138
+ def __call__(self, fn):
139
+ """Decorator to catch and hide warnings without visual nesting."""
140
+
141
+ @wraps(fn)
142
+ def wrapper(*args, **kwargs):
143
+ with warnings.catch_warnings():
144
+ warnings.simplefilter("ignore", self.category)
145
+ return fn(*args, **kwargs)
146
+
147
+ return wrapper
148
+
149
+ def __repr__(self):
150
+ args = []
151
+ if self._record:
152
+ args.append("record=True")
153
+ if self._module is not sys.modules["warnings"]:
154
+ args.append("module=%r" % self._module)
155
+ name = type(self).__name__
156
+ return "%s(%s)" % (name, ", ".join(args))
157
+
158
+ def __enter__(self):
159
+ if self._entered:
160
+ raise RuntimeError("Cannot enter %r twice" % self)
161
+ self._entered = True
162
+ self._filters = self._module.filters
163
+ self._module.filters = self._filters[:]
164
+ self._showwarning = self._module.showwarning
165
+ warnings.simplefilter("ignore", self.category)
166
+
167
+ def __exit__(self, *exc_info):
168
+ if not self._entered:
169
+ raise RuntimeError("Cannot exit %r without entering first" % self)
170
+ self._module.filters = self._filters
171
+ self._module.showwarning = self._showwarning
172
+ self.log[:] = []
173
+
174
+
175
+ def assert_allclose(
176
+ actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True
177
+ ):
178
+ """dtype-aware variant of numpy.testing.assert_allclose
179
+
180
+ This variant introspects the least precise floating point dtype
181
+ in the input argument and automatically sets the relative tolerance
182
+ parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64
183
+ in scikit-learn).
184
+
185
+ `atol` is always left to 0. by default. It should be adjusted manually
186
+ to an assertion-specific value in case there are null values expected
187
+ in `desired`.
188
+
189
+ The aggregate tolerance is `atol + rtol * abs(desired)`.
190
+
191
+ Parameters
192
+ ----------
193
+ actual : array_like
194
+ Array obtained.
195
+ desired : array_like
196
+ Array desired.
197
+ rtol : float, optional, default=None
198
+ Relative tolerance.
199
+ If None, it is set based on the provided arrays' dtypes.
200
+ atol : float, optional, default=0.
201
+ Absolute tolerance.
202
+ equal_nan : bool, optional, default=True
203
+ If True, NaNs will compare equal.
204
+ err_msg : str, optional, default=''
205
+ The error message to be printed in case of failure.
206
+ verbose : bool, optional, default=True
207
+ If True, the conflicting values are appended to the error message.
208
+
209
+ Raises
210
+ ------
211
+ AssertionError
212
+ If actual and desired are not equal up to specified precision.
213
+
214
+ See Also
215
+ --------
216
+ numpy.testing.assert_allclose
217
+
218
+ Examples
219
+ --------
220
+ >>> import numpy as np
221
+ >>> from sklearn.utils._testing import assert_allclose
222
+ >>> x = [1e-5, 1e-3, 1e-1]
223
+ >>> y = np.arccos(np.cos(x))
224
+ >>> assert_allclose(x, y, rtol=1e-5, atol=0)
225
+ >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32)
226
+ >>> assert_allclose(a, 1e-5)
227
+ """
228
+ dtypes = []
229
+
230
+ actual, desired = np.asanyarray(actual), np.asanyarray(desired)
231
+ dtypes = [actual.dtype, desired.dtype]
232
+
233
+ if rtol is None:
234
+ rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes]
235
+ rtol = max(rtols)
236
+
237
+ np_assert_allclose(
238
+ actual,
239
+ desired,
240
+ rtol=rtol,
241
+ atol=atol,
242
+ equal_nan=equal_nan,
243
+ err_msg=err_msg,
244
+ verbose=verbose,
245
+ )
246
+
247
+
248
+ def assert_allclose_dense_sparse(x, y, rtol=1e-07, atol=1e-9, err_msg=""):
249
+ """Assert allclose for sparse and dense data.
250
+
251
+ Both x and y need to be either sparse or dense, they
252
+ can't be mixed.
253
+
254
+ Parameters
255
+ ----------
256
+ x : {array-like, sparse matrix}
257
+ First array to compare.
258
+
259
+ y : {array-like, sparse matrix}
260
+ Second array to compare.
261
+
262
+ rtol : float, default=1e-07
263
+ relative tolerance; see numpy.allclose.
264
+
265
+ atol : float, default=1e-9
266
+ absolute tolerance; see numpy.allclose. Note that the default here is
267
+ more tolerant than the default for numpy.testing.assert_allclose, where
268
+ atol=0.
269
+
270
+ err_msg : str, default=''
271
+ Error message to raise.
272
+ """
273
+ if sp.sparse.issparse(x) and sp.sparse.issparse(y):
274
+ x = x.tocsr()
275
+ y = y.tocsr()
276
+ x.sum_duplicates()
277
+ y.sum_duplicates()
278
+ assert_array_equal(x.indices, y.indices, err_msg=err_msg)
279
+ assert_array_equal(x.indptr, y.indptr, err_msg=err_msg)
280
+ assert_allclose(x.data, y.data, rtol=rtol, atol=atol, err_msg=err_msg)
281
+ elif not sp.sparse.issparse(x) and not sp.sparse.issparse(y):
282
+ # both dense
283
+ assert_allclose(x, y, rtol=rtol, atol=atol, err_msg=err_msg)
284
+ else:
285
+ raise ValueError(
286
+ "Can only compare two sparse matrices, not a sparse matrix and an array."
287
+ )
288
+
289
+
290
+ def set_random_state(estimator, random_state=0):
291
+ """Set random state of an estimator if it has the `random_state` param.
292
+
293
+ Parameters
294
+ ----------
295
+ estimator : object
296
+ The estimator.
297
+ random_state : int, RandomState instance or None, default=0
298
+ Pseudo random number generator state.
299
+ Pass an int for reproducible results across multiple function calls.
300
+ See :term:`Glossary <random_state>`.
301
+ """
302
+ if "random_state" in estimator.get_params():
303
+ estimator.set_params(random_state=random_state)
304
+
305
+
306
+ def _is_numpydoc():
307
+ try:
308
+ import numpydoc # noqa: F401
309
+ except (ImportError, AssertionError):
310
+ return False
311
+ else:
312
+ return True
313
+
314
+
315
+ try:
316
+ _check_array_api_dispatch(True)
317
+ ARRAY_API_COMPAT_FUNCTIONAL = True
318
+ except (ImportError, RuntimeError):
319
+ ARRAY_API_COMPAT_FUNCTIONAL = False
320
+
321
+ try:
322
+ import pytest
323
+
324
+ skip_if_32bit = pytest.mark.skipif(_IS_32BIT, reason="skipped on 32bit platforms")
325
+ fails_if_unstable_openblas = pytest.mark.xfail(
326
+ _in_unstable_openblas_configuration(),
327
+ reason="OpenBLAS is unstable for this configuration",
328
+ )
329
+ skip_if_no_parallel = pytest.mark.skipif(
330
+ not joblib.parallel.mp, reason="joblib is in serial mode"
331
+ )
332
+ skip_if_array_api_compat_not_configured = pytest.mark.skipif(
333
+ not ARRAY_API_COMPAT_FUNCTIONAL,
334
+ reason="SCIPY_ARRAY_API not set, or versions of NumPy/SciPy too old.",
335
+ )
336
+
337
+ # Decorator for tests involving both BLAS calls and multiprocessing.
338
+ #
339
+ # Under POSIX (e.g. Linux or OSX), using multiprocessing in conjunction
340
+ # with some implementation of BLAS (or other libraries that manage an
341
+ # internal posix thread pool) can cause a crash or a freeze of the Python
342
+ # process.
343
+ #
344
+ # In practice all known packaged distributions (from Linux distros or
345
+ # Anaconda) of BLAS under Linux seems to be safe. So we this problem seems
346
+ # to only impact OSX users.
347
+ #
348
+ # This wrapper makes it possible to skip tests that can possibly cause
349
+ # this crash under OS X with.
350
+ #
351
+ # Under Python 3.4+ it is possible to use the `forkserver` start method
352
+ # for multiprocessing to avoid this issue. However it can cause pickling
353
+ # errors on interactively defined functions. It therefore not enabled by
354
+ # default.
355
+
356
+ if_safe_multiprocessing_with_blas = pytest.mark.skipif(
357
+ sys.platform == "darwin", reason="Possible multi-process bug with some BLAS"
358
+ )
359
+ skip_if_no_numpydoc = pytest.mark.skipif(
360
+ not _is_numpydoc(),
361
+ reason="numpydoc is required to test the docstrings",
362
+ )
363
+ except ImportError:
364
+ pass
365
+
366
+
367
+ def check_skip_network():
368
+ if int(os.environ.get("SKLEARN_SKIP_NETWORK_TESTS", 0)):
369
+ raise SkipTest("Text tutorial requires large dataset download")
370
+
371
+
372
+ def _delete_folder(folder_path, warn=False):
373
+ """Utility function to cleanup a temporary folder if still existing.
374
+
375
+ Copy from joblib.pool (for independence).
376
+ """
377
+ try:
378
+ if os.path.exists(folder_path):
379
+ # This can fail under windows,
380
+ # but will succeed when called by atexit
381
+ shutil.rmtree(folder_path)
382
+ except OSError:
383
+ if warn:
384
+ warnings.warn("Could not delete temporary folder %s" % folder_path)
385
+
386
+
387
+ class TempMemmap:
388
+ """
389
+ Parameters
390
+ ----------
391
+ data
392
+ mmap_mode : str, default='r'
393
+ """
394
+
395
+ def __init__(self, data, mmap_mode="r"):
396
+ self.mmap_mode = mmap_mode
397
+ self.data = data
398
+
399
+ def __enter__(self):
400
+ data_read_only, self.temp_folder = create_memmap_backed_data(
401
+ self.data, mmap_mode=self.mmap_mode, return_folder=True
402
+ )
403
+ return data_read_only
404
+
405
+ def __exit__(self, exc_type, exc_val, exc_tb):
406
+ _delete_folder(self.temp_folder)
407
+
408
+
409
+ def create_memmap_backed_data(data, mmap_mode="r", return_folder=False):
410
+ """
411
+ Parameters
412
+ ----------
413
+ data
414
+ mmap_mode : str, default='r'
415
+ return_folder : bool, default=False
416
+ """
417
+ temp_folder = tempfile.mkdtemp(prefix="sklearn_testing_")
418
+ atexit.register(functools.partial(_delete_folder, temp_folder, warn=True))
419
+ filename = op.join(temp_folder, "data.pkl")
420
+ joblib.dump(data, filename)
421
+ memmap_backed_data = joblib.load(filename, mmap_mode=mmap_mode)
422
+ result = (
423
+ memmap_backed_data if not return_folder else (memmap_backed_data, temp_folder)
424
+ )
425
+ return result
426
+
427
+
428
+ # Utils to test docstrings
429
+
430
+
431
+ def _get_args(function, varargs=False):
432
+ """Helper to get function arguments."""
433
+
434
+ try:
435
+ params = signature(function).parameters
436
+ except ValueError:
437
+ # Error on builtin C function
438
+ return []
439
+ args = [
440
+ key
441
+ for key, param in params.items()
442
+ if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)
443
+ ]
444
+ if varargs:
445
+ varargs = [
446
+ param.name
447
+ for param in params.values()
448
+ if param.kind == param.VAR_POSITIONAL
449
+ ]
450
+ if len(varargs) == 0:
451
+ varargs = None
452
+ return args, varargs
453
+ else:
454
+ return args
455
+
456
+
457
+ def _get_func_name(func):
458
+ """Get function full name.
459
+
460
+ Parameters
461
+ ----------
462
+ func : callable
463
+ The function object.
464
+
465
+ Returns
466
+ -------
467
+ name : str
468
+ The function name.
469
+ """
470
+ parts = []
471
+ module = inspect.getmodule(func)
472
+ if module:
473
+ parts.append(module.__name__)
474
+
475
+ qualname = func.__qualname__
476
+ if qualname != func.__name__:
477
+ parts.append(qualname[: qualname.find(".")])
478
+
479
+ parts.append(func.__name__)
480
+ return ".".join(parts)
481
+
482
+
483
+ def check_docstring_parameters(func, doc=None, ignore=None):
484
+ """Helper to check docstring.
485
+
486
+ Parameters
487
+ ----------
488
+ func : callable
489
+ The function object to test.
490
+ doc : str, default=None
491
+ Docstring if it is passed manually to the test.
492
+ ignore : list, default=None
493
+ Parameters to ignore.
494
+
495
+ Returns
496
+ -------
497
+ incorrect : list
498
+ A list of string describing the incorrect results.
499
+ """
500
+ from numpydoc import docscrape
501
+
502
+ incorrect = []
503
+ ignore = [] if ignore is None else ignore
504
+
505
+ func_name = _get_func_name(func)
506
+ if not func_name.startswith("sklearn.") or func_name.startswith(
507
+ "sklearn.externals"
508
+ ):
509
+ return incorrect
510
+ # Don't check docstring for property-functions
511
+ if inspect.isdatadescriptor(func):
512
+ return incorrect
513
+ # Don't check docstring for setup / teardown pytest functions
514
+ if func_name.split(".")[-1] in ("setup_module", "teardown_module"):
515
+ return incorrect
516
+ # Dont check estimator_checks module
517
+ if func_name.split(".")[2] == "estimator_checks":
518
+ return incorrect
519
+ # Get the arguments from the function signature
520
+ param_signature = list(filter(lambda x: x not in ignore, _get_args(func)))
521
+ # drop self
522
+ if len(param_signature) > 0 and param_signature[0] == "self":
523
+ param_signature.remove("self")
524
+
525
+ # Analyze function's docstring
526
+ if doc is None:
527
+ records = []
528
+ with warnings.catch_warnings(record=True):
529
+ warnings.simplefilter("error", UserWarning)
530
+ try:
531
+ doc = docscrape.FunctionDoc(func)
532
+ except UserWarning as exp:
533
+ if "potentially wrong underline length" in str(exp):
534
+ # Catch warning raised as of numpydoc 1.2 when
535
+ # the underline length for a section of a docstring
536
+ # is not consistent.
537
+ message = str(exp).split("\n")[:3]
538
+ incorrect += [f"In function: {func_name}"] + message
539
+ return incorrect
540
+ records.append(str(exp))
541
+ except Exception as exp:
542
+ incorrect += [func_name + " parsing error: " + str(exp)]
543
+ return incorrect
544
+ if len(records):
545
+ raise RuntimeError("Error for %s:\n%s" % (func_name, records[0]))
546
+
547
+ param_docs = []
548
+ for name, type_definition, param_doc in doc["Parameters"]:
549
+ # Type hints are empty only if parameter name ended with :
550
+ if not type_definition.strip():
551
+ if ":" in name and name[: name.index(":")][-1:].strip():
552
+ incorrect += [
553
+ func_name
554
+ + " There was no space between the param name and colon (%r)" % name
555
+ ]
556
+ elif name.rstrip().endswith(":"):
557
+ incorrect += [
558
+ func_name
559
+ + " Parameter %r has an empty type spec. Remove the colon"
560
+ % (name.lstrip())
561
+ ]
562
+
563
+ # Create a list of parameters to compare with the parameters gotten
564
+ # from the func signature
565
+ if "*" not in name:
566
+ param_docs.append(name.split(":")[0].strip("` "))
567
+
568
+ # If one of the docstring's parameters had an error then return that
569
+ # incorrect message
570
+ if len(incorrect) > 0:
571
+ return incorrect
572
+
573
+ # Remove the parameters that should be ignored from list
574
+ param_docs = list(filter(lambda x: x not in ignore, param_docs))
575
+
576
+ # The following is derived from pytest, Copyright (c) 2004-2017 Holger
577
+ # Krekel and others, Licensed under MIT License. See
578
+ # https://github.com/pytest-dev/pytest
579
+
580
+ message = []
581
+ for i in range(min(len(param_docs), len(param_signature))):
582
+ if param_signature[i] != param_docs[i]:
583
+ message += [
584
+ "There's a parameter name mismatch in function"
585
+ " docstring w.r.t. function signature, at index %s"
586
+ " diff: %r != %r" % (i, param_signature[i], param_docs[i])
587
+ ]
588
+ break
589
+ if len(param_signature) > len(param_docs):
590
+ message += [
591
+ "Parameters in function docstring have less items w.r.t."
592
+ " function signature, first missing item: %s"
593
+ % param_signature[len(param_docs)]
594
+ ]
595
+
596
+ elif len(param_signature) < len(param_docs):
597
+ message += [
598
+ "Parameters in function docstring have more items w.r.t."
599
+ " function signature, first extra item: %s"
600
+ % param_docs[len(param_signature)]
601
+ ]
602
+
603
+ # If there wasn't any difference in the parameters themselves between
604
+ # docstring and signature including having the same length then return
605
+ # empty list
606
+ if len(message) == 0:
607
+ return []
608
+
609
+ import difflib
610
+ import pprint
611
+
612
+ param_docs_formatted = pprint.pformat(param_docs).splitlines()
613
+ param_signature_formatted = pprint.pformat(param_signature).splitlines()
614
+
615
+ message += ["Full diff:"]
616
+
617
+ message.extend(
618
+ line.strip()
619
+ for line in difflib.ndiff(param_signature_formatted, param_docs_formatted)
620
+ )
621
+
622
+ incorrect.extend(message)
623
+
624
+ # Prepend function name
625
+ incorrect = ["In function: " + func_name] + incorrect
626
+
627
+ return incorrect
628
+
629
+
630
+ def _check_item_included(item_name, args):
631
+ """Helper to check if item should be included in checking."""
632
+ if args.include is not True and item_name not in args.include:
633
+ return False
634
+ if args.exclude is not None and item_name in args.exclude:
635
+ return False
636
+ return True
637
+
638
+
639
+ def _diff_key(line):
640
+ """Key for grouping output from `context_diff`."""
641
+ if line.startswith(" "):
642
+ return " "
643
+ elif line.startswith("- "):
644
+ return "- "
645
+ elif line.startswith("+ "):
646
+ return "+ "
647
+ elif line.startswith("! "):
648
+ return "! "
649
+ return None
650
+
651
+
652
+ def _get_diff_msg(docstrings_grouped):
653
+ """Get message showing the difference between type/desc docstrings of all objects.
654
+
655
+ `docstrings_grouped` keys should be the type/desc docstrings and values are a list
656
+ of objects with that docstring. Objects with the same type/desc docstring are
657
+ thus grouped together.
658
+ """
659
+ msg_diff = ""
660
+ ref_str = ""
661
+ ref_group = []
662
+ for docstring, group in docstrings_grouped.items():
663
+ if not ref_str and not ref_group:
664
+ ref_str += docstring
665
+ ref_group.extend(group)
666
+ diff = list(
667
+ context_diff(
668
+ ref_str.split(),
669
+ docstring.split(),
670
+ fromfile=str(ref_group),
671
+ tofile=str(group),
672
+ n=8,
673
+ )
674
+ )
675
+ # Add header
676
+ msg_diff += "".join((diff[:3]))
677
+ # Group consecutive 'diff' words to shorten error message
678
+ for start, group in groupby(diff[3:], key=_diff_key):
679
+ if start is None:
680
+ msg_diff += "\n" + "\n".join(group)
681
+ else:
682
+ msg_diff += "\n" + start + " ".join(word[2:] for word in group)
683
+ # Add new lines at end of diff, to separate comparisons
684
+ msg_diff += "\n\n"
685
+ return msg_diff
686
+
687
+
688
+ def _check_consistency_items(
689
+ items_docs,
690
+ type_or_desc,
691
+ section,
692
+ n_objects,
693
+ descr_regex_pattern="",
694
+ ignore_types=tuple(),
695
+ ):
696
+ """Helper to check docstring consistency of all `items_docs`.
697
+
698
+ If item is not present in all objects, checking is skipped and warning raised.
699
+ If `regex` provided, match descriptions to all descriptions.
700
+
701
+ Parameters
702
+ ----------
703
+ items_doc : dict of dict of str
704
+ Dictionary where the key is the string type or description, value is
705
+ a dictionary where the key is "type description" or "description"
706
+ and the value is a list of object names with the same string type or
707
+ description.
708
+
709
+ type_or_desc : {"type description", "description"}
710
+ Whether to check type description or description between objects.
711
+
712
+ section : {"Parameters", "Attributes", "Returns"}
713
+ Name of the section type.
714
+
715
+ n_objects : int
716
+ Total number of objects.
717
+
718
+ descr_regex_pattern : str, default=""
719
+ Regex pattern to match for description of all objects.
720
+ Ignored when `type_or_desc="type description".
721
+
722
+ ignore_types : tuple of str, default=()
723
+ Tuple of parameter/attribute/return names for which type description
724
+ matching is ignored. Ignored when `type_or_desc="description".
725
+ """
726
+ skipped = []
727
+ for item_name, docstrings_grouped in items_docs.items():
728
+ # If item not found in all objects, skip
729
+ if sum([len(objs) for objs in docstrings_grouped.values()]) < n_objects:
730
+ skipped.append(item_name)
731
+ # If regex provided, match to all descriptions
732
+ elif type_or_desc == "description" and descr_regex_pattern:
733
+ not_matched = []
734
+ for docstring, group in docstrings_grouped.items():
735
+ if not re.search(descr_regex_pattern, docstring):
736
+ not_matched.extend(group)
737
+ if not_matched:
738
+ msg = textwrap.fill(
739
+ f"The description of {section[:-1]} '{item_name}' in {not_matched}"
740
+ f" does not match 'descr_regex_pattern': {descr_regex_pattern} "
741
+ )
742
+ raise AssertionError(msg)
743
+ # Skip type checking for items in `ignore_types`
744
+ elif type_or_desc == "type specification" and item_name in ignore_types:
745
+ continue
746
+ # Otherwise, if more than one key, docstrings not consistent between objects
747
+ elif len(docstrings_grouped.keys()) > 1:
748
+ msg_diff = _get_diff_msg(docstrings_grouped)
749
+ obj_groups = " and ".join(
750
+ str(group) for group in docstrings_grouped.values()
751
+ )
752
+ msg = textwrap.fill(
753
+ f"The {type_or_desc} of {section[:-1]} '{item_name}' is inconsistent "
754
+ f"between {obj_groups}:"
755
+ )
756
+ msg += msg_diff
757
+ raise AssertionError(msg)
758
+ if skipped:
759
+ warnings.warn(
760
+ f"Checking was skipped for {section}: {skipped} as they were "
761
+ "not found in all objects."
762
+ )
763
+
764
+
765
+ def assert_docstring_consistency(
766
+ objects,
767
+ include_params=False,
768
+ exclude_params=None,
769
+ include_attrs=False,
770
+ exclude_attrs=None,
771
+ include_returns=False,
772
+ exclude_returns=None,
773
+ descr_regex_pattern=None,
774
+ ignore_types=tuple(),
775
+ ):
776
+ r"""Check consistency between docstring parameters/attributes/returns of objects.
777
+
778
+ Checks if parameters/attributes/returns have the same type specification and
779
+ description (ignoring whitespace) across `objects`. Intended to be used for
780
+ related classes/functions/data descriptors.
781
+
782
+ Entries that do not appear across all `objects` are ignored.
783
+
784
+ Parameters
785
+ ----------
786
+ objects : list of {classes, functions, data descriptors}
787
+ Objects to check.
788
+ Objects may be classes, functions or data descriptors with docstrings that
789
+ can be parsed by numpydoc.
790
+
791
+ include_params : list of str or bool, default=False
792
+ List of parameters to be included. If True, all parameters are included,
793
+ if False, checking is skipped for parameters.
794
+ Can only be set if `exclude_params` is None.
795
+
796
+ exclude_params : list of str or None, default=None
797
+ List of parameters to be excluded. If None, no parameters are excluded.
798
+ Can only be set if `include_params` is True.
799
+
800
+ include_attrs : list of str or bool, default=False
801
+ List of attributes to be included. If True, all attributes are included,
802
+ if False, checking is skipped for attributes.
803
+ Can only be set if `exclude_attrs` is None.
804
+
805
+ exclude_attrs : list of str or None, default=None
806
+ List of attributes to be excluded. If None, no attributes are excluded.
807
+ Can only be set if `include_attrs` is True.
808
+
809
+ include_returns : list of str or bool, default=False
810
+ List of returns to be included. If True, all returns are included,
811
+ if False, checking is skipped for returns.
812
+ Can only be set if `exclude_returns` is None.
813
+
814
+ exclude_returns : list of str or None, default=None
815
+ List of returns to be excluded. If None, no returns are excluded.
816
+ Can only be set if `include_returns` is True.
817
+
818
+ descr_regex_pattern : str, default=None
819
+ Regular expression to match to all descriptions of included
820
+ parameters/attributes/returns. If None, will revert to default behavior
821
+ of comparing descriptions between objects.
822
+
823
+ ignore_types : tuple of str, default=tuple()
824
+ Tuple of parameter/attribute/return names to exclude from type description
825
+ matching between objects.
826
+
827
+ Examples
828
+ --------
829
+ >>> from sklearn.metrics import (accuracy_score, classification_report,
830
+ ... mean_absolute_error, mean_squared_error, median_absolute_error)
831
+ >>> from sklearn.utils._testing import assert_docstring_consistency
832
+ ... # doctest: +SKIP
833
+ >>> assert_docstring_consistency([mean_absolute_error, mean_squared_error],
834
+ ... include_params=['y_true', 'y_pred', 'sample_weight']) # doctest: +SKIP
835
+ >>> assert_docstring_consistency([median_absolute_error, mean_squared_error],
836
+ ... include_params=True) # doctest: +SKIP
837
+ >>> assert_docstring_consistency([accuracy_score, classification_report],
838
+ ... include_params=["y_true"],
839
+ ... descr_regex_pattern=r"Ground truth \(correct\) (labels|target values)")
840
+ ... # doctest: +SKIP
841
+ """
842
+ from numpydoc.docscrape import NumpyDocString
843
+
844
+ Args = namedtuple("args", ["include", "exclude", "arg_name"])
845
+
846
+ def _create_args(include, exclude, arg_name, section_name):
847
+ if exclude and include is not True:
848
+ raise TypeError(
849
+ f"The 'exclude_{arg_name}' argument can be set only when the "
850
+ f"'include_{arg_name}' argument is True."
851
+ )
852
+ if include is False:
853
+ return {}
854
+ return {section_name: Args(include, exclude, arg_name)}
855
+
856
+ section_args = {
857
+ **_create_args(include_params, exclude_params, "params", "Parameters"),
858
+ **_create_args(include_attrs, exclude_attrs, "attrs", "Attributes"),
859
+ **_create_args(include_returns, exclude_returns, "returns", "Returns"),
860
+ }
861
+
862
+ objects_doc = dict()
863
+ for obj in objects:
864
+ if (
865
+ inspect.isdatadescriptor(obj)
866
+ or inspect.isfunction(obj)
867
+ or inspect.isclass(obj)
868
+ ):
869
+ objects_doc[obj.__name__] = NumpyDocString(inspect.getdoc(obj))
870
+ else:
871
+ raise TypeError(
872
+ "All 'objects' must be one of: function, class or descriptor, "
873
+ f"got a: {type(obj)}."
874
+ )
875
+
876
+ n_objects = len(objects)
877
+ for section, args in section_args.items():
878
+ type_items = defaultdict(lambda: defaultdict(list))
879
+ desc_items = defaultdict(lambda: defaultdict(list))
880
+ for obj_name, obj_doc in objects_doc.items():
881
+ for item_name, type_def, desc in obj_doc[section]:
882
+ if _check_item_included(item_name, args):
883
+ # Normalize white space
884
+ type_def = " ".join(type_def.strip().split())
885
+ desc = " ".join(chain.from_iterable(line.split() for line in desc))
886
+ # Use string type/desc as key, to group consistent objs together
887
+ type_items[item_name][type_def].append(obj_name)
888
+ desc_items[item_name][desc].append(obj_name)
889
+
890
+ _check_consistency_items(
891
+ type_items,
892
+ "type specification",
893
+ section,
894
+ n_objects,
895
+ ignore_types=ignore_types,
896
+ )
897
+ _check_consistency_items(
898
+ desc_items,
899
+ "description",
900
+ section,
901
+ n_objects,
902
+ descr_regex_pattern=descr_regex_pattern,
903
+ )
904
+
905
+
906
+ def assert_run_python_script_without_output(source_code, pattern=".+", timeout=60):
907
+ """Utility to check assertions in an independent Python subprocess.
908
+
909
+ The script provided in the source code should return 0 and the stdtout +
910
+ stderr should not match the pattern `pattern`.
911
+
912
+ This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle
913
+
914
+ Parameters
915
+ ----------
916
+ source_code : str
917
+ The Python source code to execute.
918
+ pattern : str
919
+ Pattern that the stdout + stderr should not match. By default, unless
920
+ stdout + stderr are both empty, an error will be raised.
921
+ timeout : int, default=60
922
+ Time in seconds before timeout.
923
+ """
924
+ fd, source_file = tempfile.mkstemp(suffix="_src_test_sklearn.py")
925
+ os.close(fd)
926
+ try:
927
+ with open(source_file, "wb") as f:
928
+ f.write(source_code.encode("utf-8"))
929
+ cmd = [sys.executable, source_file]
930
+ cwd = op.normpath(op.join(op.dirname(sklearn.__file__), ".."))
931
+ env = os.environ.copy()
932
+ try:
933
+ env["PYTHONPATH"] = os.pathsep.join([cwd, env["PYTHONPATH"]])
934
+ except KeyError:
935
+ env["PYTHONPATH"] = cwd
936
+ kwargs = {"cwd": cwd, "stderr": STDOUT, "env": env}
937
+ # If coverage is running, pass the config file to the subprocess
938
+ coverage_rc = os.environ.get("COVERAGE_PROCESS_START")
939
+ if coverage_rc:
940
+ kwargs["env"]["COVERAGE_PROCESS_START"] = coverage_rc
941
+
942
+ kwargs["timeout"] = timeout
943
+ try:
944
+ try:
945
+ out = check_output(cmd, **kwargs)
946
+ except CalledProcessError as e:
947
+ raise RuntimeError(
948
+ "script errored with output:\n%s" % e.output.decode("utf-8")
949
+ )
950
+
951
+ out = out.decode("utf-8")
952
+ if re.search(pattern, out):
953
+ if pattern == ".+":
954
+ expectation = "Expected no output"
955
+ else:
956
+ expectation = f"The output was not supposed to match {pattern!r}"
957
+
958
+ message = f"{expectation}, got the following output instead: {out!r}"
959
+ raise AssertionError(message)
960
+ except TimeoutExpired as e:
961
+ raise RuntimeError(
962
+ "script timeout, output so far:\n%s" % e.output.decode("utf-8")
963
+ )
964
+ finally:
965
+ os.unlink(source_file)
966
+
967
+
968
+ def _convert_container(
969
+ container,
970
+ constructor_name,
971
+ columns_name=None,
972
+ dtype=None,
973
+ minversion=None,
974
+ categorical_feature_names=None,
975
+ ):
976
+ """Convert a given container to a specific array-like with a dtype.
977
+
978
+ Parameters
979
+ ----------
980
+ container : array-like
981
+ The container to convert.
982
+ constructor_name : {"list", "tuple", "array", "sparse", "dataframe", \
983
+ "series", "index", "slice", "sparse_csr", "sparse_csc", \
984
+ "sparse_csr_array", "sparse_csc_array", "pyarrow", "polars", \
985
+ "polars_series"}
986
+ The type of the returned container.
987
+ columns_name : index or array-like, default=None
988
+ For pandas container supporting `columns_names`, it will affect
989
+ specific names.
990
+ dtype : dtype, default=None
991
+ Force the dtype of the container. Does not apply to `"slice"`
992
+ container.
993
+ minversion : str, default=None
994
+ Minimum version for package to install.
995
+ categorical_feature_names : list of str, default=None
996
+ List of column names to cast to categorical dtype.
997
+
998
+ Returns
999
+ -------
1000
+ converted_container
1001
+ """
1002
+ if constructor_name == "list":
1003
+ if dtype is None:
1004
+ return list(container)
1005
+ else:
1006
+ return np.asarray(container, dtype=dtype).tolist()
1007
+ elif constructor_name == "tuple":
1008
+ if dtype is None:
1009
+ return tuple(container)
1010
+ else:
1011
+ return tuple(np.asarray(container, dtype=dtype).tolist())
1012
+ elif constructor_name == "array":
1013
+ return np.asarray(container, dtype=dtype)
1014
+ elif constructor_name in ("pandas", "dataframe"):
1015
+ pd = pytest.importorskip("pandas", minversion=minversion)
1016
+ result = pd.DataFrame(container, columns=columns_name, dtype=dtype, copy=False)
1017
+ if categorical_feature_names is not None:
1018
+ for col_name in categorical_feature_names:
1019
+ result[col_name] = result[col_name].astype("category")
1020
+ return result
1021
+ elif constructor_name == "pyarrow":
1022
+ pa = pytest.importorskip("pyarrow", minversion=minversion)
1023
+ array = np.asarray(container)
1024
+ array = array[:, None] if array.ndim == 1 else array
1025
+ if columns_name is None:
1026
+ columns_name = [f"col{i}" for i in range(array.shape[1])]
1027
+ data = {name: array[:, i] for i, name in enumerate(columns_name)}
1028
+ result = pa.Table.from_pydict(data)
1029
+ if categorical_feature_names is not None:
1030
+ for col_idx, col_name in enumerate(result.column_names):
1031
+ if col_name in categorical_feature_names:
1032
+ result = result.set_column(
1033
+ col_idx, col_name, result.column(col_name).dictionary_encode()
1034
+ )
1035
+ return result
1036
+ elif constructor_name == "polars":
1037
+ pl = pytest.importorskip("polars", minversion=minversion)
1038
+ result = pl.DataFrame(container, schema=columns_name, orient="row")
1039
+ if categorical_feature_names is not None:
1040
+ for col_name in categorical_feature_names:
1041
+ result = result.with_columns(pl.col(col_name).cast(pl.Categorical))
1042
+ return result
1043
+ elif constructor_name == "series":
1044
+ pd = pytest.importorskip("pandas", minversion=minversion)
1045
+ return pd.Series(container, dtype=dtype)
1046
+ elif constructor_name == "pyarrow_array":
1047
+ pa = pytest.importorskip("pyarrow", minversion=minversion)
1048
+ return pa.array(container)
1049
+ elif constructor_name == "polars_series":
1050
+ pl = pytest.importorskip("polars", minversion=minversion)
1051
+ return pl.Series(values=container)
1052
+ elif constructor_name == "index":
1053
+ pd = pytest.importorskip("pandas", minversion=minversion)
1054
+ return pd.Index(container, dtype=dtype)
1055
+ elif constructor_name == "slice":
1056
+ return slice(container[0], container[1])
1057
+ elif "sparse" in constructor_name:
1058
+ if not sp.sparse.issparse(container):
1059
+ # For scipy >= 1.13, sparse array constructed from 1d array may be
1060
+ # 1d or raise an exception. To avoid this, we make sure that the
1061
+ # input container is 2d. For more details, see
1062
+ # https://github.com/scipy/scipy/pull/18530#issuecomment-1878005149
1063
+ container = np.atleast_2d(container)
1064
+
1065
+ if constructor_name in ("sparse", "sparse_csr"):
1066
+ # sparse and sparse_csr are equivalent for legacy reasons
1067
+ return sp.sparse.csr_matrix(container, dtype=dtype)
1068
+ elif constructor_name == "sparse_csr_array":
1069
+ return sp.sparse.csr_array(container, dtype=dtype)
1070
+ elif constructor_name == "sparse_csc":
1071
+ return sp.sparse.csc_matrix(container, dtype=dtype)
1072
+ elif constructor_name == "sparse_csc_array":
1073
+ return sp.sparse.csc_array(container, dtype=dtype)
1074
+
1075
+
1076
+ def raises(expected_exc_type, match=None, may_pass=False, err_msg=None):
1077
+ """Context manager to ensure exceptions are raised within a code block.
1078
+
1079
+ This is similar to and inspired from pytest.raises, but supports a few
1080
+ other cases.
1081
+
1082
+ This is only intended to be used in estimator_checks.py where we don't
1083
+ want to use pytest. In the rest of the code base, just use pytest.raises
1084
+ instead.
1085
+
1086
+ Parameters
1087
+ ----------
1088
+ excepted_exc_type : Exception or list of Exception
1089
+ The exception that should be raised by the block. If a list, the block
1090
+ should raise one of the exceptions.
1091
+ match : str or list of str, default=None
1092
+ A regex that the exception message should match. If a list, one of
1093
+ the entries must match. If None, match isn't enforced.
1094
+ may_pass : bool, default=False
1095
+ If True, the block is allowed to not raise an exception. Useful in
1096
+ cases where some estimators may support a feature but others must
1097
+ fail with an appropriate error message. By default, the context
1098
+ manager will raise an exception if the block does not raise an
1099
+ exception.
1100
+ err_msg : str, default=None
1101
+ If the context manager fails (e.g. the block fails to raise the
1102
+ proper exception, or fails to match), then an AssertionError is
1103
+ raised with this message. By default, an AssertionError is raised
1104
+ with a default error message (depends on the kind of failure). Use
1105
+ this to indicate how users should fix their estimators to pass the
1106
+ checks.
1107
+
1108
+ Attributes
1109
+ ----------
1110
+ raised_and_matched : bool
1111
+ True if an exception was raised and a match was found, False otherwise.
1112
+ """
1113
+ return _Raises(expected_exc_type, match, may_pass, err_msg)
1114
+
1115
+
1116
+ class _Raises(contextlib.AbstractContextManager):
1117
+ # see raises() for parameters
1118
+ def __init__(self, expected_exc_type, match, may_pass, err_msg):
1119
+ self.expected_exc_types = (
1120
+ expected_exc_type
1121
+ if isinstance(expected_exc_type, Iterable)
1122
+ else [expected_exc_type]
1123
+ )
1124
+ self.matches = [match] if isinstance(match, str) else match
1125
+ self.may_pass = may_pass
1126
+ self.err_msg = err_msg
1127
+ self.raised_and_matched = False
1128
+
1129
+ def __exit__(self, exc_type, exc_value, _):
1130
+ # see
1131
+ # https://docs.python.org/2.5/whatsnew/pep-343.html#SECTION000910000000000000000
1132
+
1133
+ if exc_type is None: # No exception was raised in the block
1134
+ if self.may_pass:
1135
+ return True # CM is happy
1136
+ else:
1137
+ err_msg = self.err_msg or f"Did not raise: {self.expected_exc_types}"
1138
+ raise AssertionError(err_msg)
1139
+
1140
+ if not any(
1141
+ issubclass(exc_type, expected_type)
1142
+ for expected_type in self.expected_exc_types
1143
+ ):
1144
+ if self.err_msg is not None:
1145
+ raise AssertionError(self.err_msg) from exc_value
1146
+ else:
1147
+ return False # will re-raise the original exception
1148
+
1149
+ if self.matches is not None:
1150
+ err_msg = self.err_msg or (
1151
+ "The error message should contain one of the following "
1152
+ "patterns:\n{}\nGot {}".format("\n".join(self.matches), str(exc_value))
1153
+ )
1154
+ if not any(re.search(match, str(exc_value)) for match in self.matches):
1155
+ raise AssertionError(err_msg) from exc_value
1156
+ self.raised_and_matched = True
1157
+
1158
+ return True
1159
+
1160
+
1161
+ class MinimalClassifier:
1162
+ """Minimal classifier implementation without inheriting from BaseEstimator.
1163
+
1164
+ This estimator should be tested with:
1165
+
1166
+ * `check_estimator` in `test_estimator_checks.py`;
1167
+ * within a `Pipeline` in `test_pipeline.py`;
1168
+ * within a `SearchCV` in `test_search.py`.
1169
+ """
1170
+
1171
+ def __init__(self, param=None):
1172
+ self.param = param
1173
+
1174
+ def get_params(self, deep=True):
1175
+ return {"param": self.param}
1176
+
1177
+ def set_params(self, **params):
1178
+ for key, value in params.items():
1179
+ setattr(self, key, value)
1180
+ return self
1181
+
1182
+ def fit(self, X, y):
1183
+ X, y = check_X_y(X, y)
1184
+ check_classification_targets(y)
1185
+ self.classes_, counts = np.unique(y, return_counts=True)
1186
+ self._most_frequent_class_idx = counts.argmax()
1187
+ return self
1188
+
1189
+ def predict_proba(self, X):
1190
+ check_is_fitted(self)
1191
+ X = check_array(X)
1192
+ proba_shape = (X.shape[0], self.classes_.size)
1193
+ y_proba = np.zeros(shape=proba_shape, dtype=np.float64)
1194
+ y_proba[:, self._most_frequent_class_idx] = 1.0
1195
+ return y_proba
1196
+
1197
+ def predict(self, X):
1198
+ y_proba = self.predict_proba(X)
1199
+ y_pred = y_proba.argmax(axis=1)
1200
+ return self.classes_[y_pred]
1201
+
1202
+ def score(self, X, y):
1203
+ from sklearn.metrics import accuracy_score
1204
+
1205
+ return accuracy_score(y, self.predict(X))
1206
+
1207
+ def __sklearn_tags__(self):
1208
+ return Tags(
1209
+ estimator_type="classifier",
1210
+ classifier_tags=ClassifierTags(),
1211
+ regressor_tags=None,
1212
+ transformer_tags=None,
1213
+ target_tags=TargetTags(required=True),
1214
+ )
1215
+
1216
+
1217
+ class MinimalRegressor:
1218
+ """Minimal regressor implementation without inheriting from BaseEstimator.
1219
+
1220
+ This estimator should be tested with:
1221
+
1222
+ * `check_estimator` in `test_estimator_checks.py`;
1223
+ * within a `Pipeline` in `test_pipeline.py`;
1224
+ * within a `SearchCV` in `test_search.py`.
1225
+ """
1226
+
1227
+ def __init__(self, param=None):
1228
+ self.param = param
1229
+
1230
+ def get_params(self, deep=True):
1231
+ return {"param": self.param}
1232
+
1233
+ def set_params(self, **params):
1234
+ for key, value in params.items():
1235
+ setattr(self, key, value)
1236
+ return self
1237
+
1238
+ def fit(self, X, y):
1239
+ X, y = check_X_y(X, y)
1240
+ self.is_fitted_ = True
1241
+ self._mean = np.mean(y)
1242
+ return self
1243
+
1244
+ def predict(self, X):
1245
+ check_is_fitted(self)
1246
+ X = check_array(X)
1247
+ return np.ones(shape=(X.shape[0],)) * self._mean
1248
+
1249
+ def score(self, X, y):
1250
+ from sklearn.metrics import r2_score
1251
+
1252
+ return r2_score(y, self.predict(X))
1253
+
1254
+ def __sklearn_tags__(self):
1255
+ return Tags(
1256
+ estimator_type="regressor",
1257
+ classifier_tags=None,
1258
+ regressor_tags=RegressorTags(),
1259
+ transformer_tags=None,
1260
+ target_tags=TargetTags(required=True),
1261
+ )
1262
+
1263
+
1264
+ class MinimalTransformer:
1265
+ """Minimal transformer implementation without inheriting from
1266
+ BaseEstimator.
1267
+
1268
+ This estimator should be tested with:
1269
+
1270
+ * `check_estimator` in `test_estimator_checks.py`;
1271
+ * within a `Pipeline` in `test_pipeline.py`;
1272
+ * within a `SearchCV` in `test_search.py`.
1273
+ """
1274
+
1275
+ def __init__(self, param=None):
1276
+ self.param = param
1277
+
1278
+ def get_params(self, deep=True):
1279
+ return {"param": self.param}
1280
+
1281
+ def set_params(self, **params):
1282
+ for key, value in params.items():
1283
+ setattr(self, key, value)
1284
+ return self
1285
+
1286
+ def fit(self, X, y=None):
1287
+ check_array(X)
1288
+ self.is_fitted_ = True
1289
+ return self
1290
+
1291
+ def transform(self, X, y=None):
1292
+ check_is_fitted(self)
1293
+ X = check_array(X)
1294
+ return X
1295
+
1296
+ def fit_transform(self, X, y=None):
1297
+ return self.fit(X, y).transform(X, y)
1298
+
1299
+ def __sklearn_tags__(self):
1300
+ return Tags(
1301
+ estimator_type="transformer",
1302
+ classifier_tags=None,
1303
+ regressor_tags=None,
1304
+ transformer_tags=TransformerTags(),
1305
+ target_tags=TargetTags(required=False),
1306
+ )
1307
+
1308
+
1309
+ def _array_api_for_tests(array_namespace, device):
1310
+ try:
1311
+ array_mod = importlib.import_module(array_namespace)
1312
+ except (ModuleNotFoundError, ImportError):
1313
+ raise SkipTest(
1314
+ f"{array_namespace} is not installed: not checking array_api input"
1315
+ )
1316
+
1317
+ if os.environ.get("SCIPY_ARRAY_API") is None:
1318
+ raise SkipTest("SCIPY_ARRAY_API is not set: not checking array_api input")
1319
+
1320
+ from sklearn.externals.array_api_compat import get_namespace
1321
+
1322
+ # First create an array using the chosen array module and then get the
1323
+ # corresponding (compatibility wrapped) array namespace based on it.
1324
+ # This is because `cupy` is not the same as the compatibility wrapped
1325
+ # namespace of a CuPy array.
1326
+ xp = get_namespace(array_mod.asarray(1))
1327
+ if (
1328
+ array_namespace == "torch"
1329
+ and device == "cuda"
1330
+ and not xp.backends.cuda.is_built()
1331
+ ):
1332
+ raise SkipTest("PyTorch test requires cuda, which is not available")
1333
+ elif array_namespace == "torch" and device == "mps":
1334
+ if os.getenv("PYTORCH_ENABLE_MPS_FALLBACK") != "1":
1335
+ # For now we need PYTORCH_ENABLE_MPS_FALLBACK=1 for all estimators to work
1336
+ # when using the MPS device.
1337
+ raise SkipTest(
1338
+ "Skipping MPS device test because PYTORCH_ENABLE_MPS_FALLBACK is not "
1339
+ "set."
1340
+ )
1341
+ if not xp.backends.mps.is_built():
1342
+ raise SkipTest(
1343
+ "MPS is not available because the current PyTorch install was not "
1344
+ "built with MPS enabled."
1345
+ )
1346
+ elif array_namespace == "cupy": # pragma: nocover
1347
+ import cupy
1348
+
1349
+ if cupy.cuda.runtime.getDeviceCount() == 0:
1350
+ raise SkipTest("CuPy test requires cuda, which is not available")
1351
+ return xp
1352
+
1353
+
1354
+ def _get_warnings_filters_info_list():
1355
+ @dataclass
1356
+ class WarningInfo:
1357
+ action: "warnings._ActionKind" # type: ignore[annotation-unchecked]
1358
+ message: str = "" # type: ignore[annotation-unchecked]
1359
+ category: type[Warning] = Warning # type: ignore[annotation-unchecked]
1360
+
1361
+ def to_filterwarning_str(self):
1362
+ if self.category.__module__ == "builtins":
1363
+ category = self.category.__name__
1364
+ else:
1365
+ category = f"{self.category.__module__}.{self.category.__name__}"
1366
+
1367
+ return f"{self.action}:{self.message}:{category}"
1368
+
1369
+ return [
1370
+ WarningInfo("error", category=DeprecationWarning),
1371
+ WarningInfo("error", category=FutureWarning),
1372
+ WarningInfo("error", category=VisibleDeprecationWarning),
1373
+ # TODO: remove when pyamg > 5.0.1
1374
+ # Avoid a deprecation warning due pkg_resources usage in pyamg.
1375
+ WarningInfo(
1376
+ "ignore",
1377
+ message="pkg_resources is deprecated as an API",
1378
+ category=DeprecationWarning,
1379
+ ),
1380
+ WarningInfo(
1381
+ "ignore",
1382
+ message="Deprecated call to `pkg_resources",
1383
+ category=DeprecationWarning,
1384
+ ),
1385
+ # pytest-cov issue https://github.com/pytest-dev/pytest-cov/issues/557 not
1386
+ # fixed although it has been closed. https://github.com/pytest-dev/pytest-cov/pull/623
1387
+ # would probably fix it.
1388
+ WarningInfo(
1389
+ "ignore",
1390
+ message=(
1391
+ "The --rsyncdir command line argument and rsyncdirs config variable are"
1392
+ " deprecated"
1393
+ ),
1394
+ category=DeprecationWarning,
1395
+ ),
1396
+ # XXX: Easiest way to ignore pandas Pyarrow DeprecationWarning in the
1397
+ # short-term. See https://github.com/pandas-dev/pandas/issues/54466 for
1398
+ # more details.
1399
+ WarningInfo(
1400
+ "ignore",
1401
+ message=r"\s*Pyarrow will become a required dependency",
1402
+ category=DeprecationWarning,
1403
+ ),
1404
+ # warnings has been fixed from dateutil main but not released yet, see
1405
+ # https://github.com/dateutil/dateutil/issues/1314
1406
+ WarningInfo(
1407
+ "ignore",
1408
+ message="datetime.datetime.utcfromtimestamp",
1409
+ category=DeprecationWarning,
1410
+ ),
1411
+ # Python 3.12 warnings from joblib fixed in master but not released yet,
1412
+ # see https://github.com/joblib/joblib/pull/1518
1413
+ WarningInfo(
1414
+ "ignore", message="ast.Num is deprecated", category=DeprecationWarning
1415
+ ),
1416
+ WarningInfo(
1417
+ "ignore", message="Attribute n is deprecated", category=DeprecationWarning
1418
+ ),
1419
+ # Python 3.12 warnings from sphinx-gallery fixed in master but not
1420
+ # released yet, see
1421
+ # https://github.com/sphinx-gallery/sphinx-gallery/pull/1242
1422
+ WarningInfo(
1423
+ "ignore", message="ast.Str is deprecated", category=DeprecationWarning
1424
+ ),
1425
+ WarningInfo(
1426
+ "ignore", message="Attribute s is deprecated", category=DeprecationWarning
1427
+ ),
1428
+ # Plotly deprecated something which we're not using, but internally it's used
1429
+ # and needs to be fixed on their side.
1430
+ # https://github.com/plotly/plotly.py/issues/4997
1431
+ WarningInfo(
1432
+ "ignore",
1433
+ message=".+scattermapbox.+deprecated.+scattermap.+instead",
1434
+ category=DeprecationWarning,
1435
+ ),
1436
+ ]
1437
+
1438
+
1439
+ def get_pytest_filterwarning_lines():
1440
+ warning_filters_info_list = _get_warnings_filters_info_list()
1441
+ return [
1442
+ warning_info.to_filterwarning_str()
1443
+ for warning_info in warning_filters_info_list
1444
+ ]
1445
+
1446
+
1447
+ def turn_warnings_into_errors():
1448
+ warnings_filters_info_list = _get_warnings_filters_info_list()
1449
+ for warning_info in warnings_filters_info_list:
1450
+ warnings.filterwarnings(
1451
+ warning_info.action,
1452
+ message=warning_info.message,
1453
+ category=warning_info.category,
1454
+ )
shared/package-files/d6/d67a2b78b4428693a07928f4b894f599e862065f27821df71ae73b29dbf36183/METADATA ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: certifi
3
+ Version: 2024.2.2
4
+ Summary: Python package for providing Mozilla's CA Bundle.
5
+ Home-page: https://github.com/certifi/python-certifi
6
+ Author: Kenneth Reitz
7
+ Author-email: me@kennethreitz.com
8
+ License: MPL-2.0
9
+ Project-URL: Source, https://github.com/certifi/python-certifi
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.6
18
+ Classifier: Programming Language :: Python :: 3.7
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Requires-Python: >=3.6
24
+ License-File: LICENSE
25
+
26
+ Certifi: Python SSL Certificates
27
+ ================================
28
+
29
+ Certifi provides Mozilla's carefully curated collection of Root Certificates for
30
+ validating the trustworthiness of SSL certificates while verifying the identity
31
+ of TLS hosts. It has been extracted from the `Requests`_ project.
32
+
33
+ Installation
34
+ ------------
35
+
36
+ ``certifi`` is available on PyPI. Simply install it with ``pip``::
37
+
38
+ $ pip install certifi
39
+
40
+ Usage
41
+ -----
42
+
43
+ To reference the installed certificate authority (CA) bundle, you can use the
44
+ built-in function::
45
+
46
+ >>> import certifi
47
+
48
+ >>> certifi.where()
49
+ '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
50
+
51
+ Or from the command line::
52
+
53
+ $ python -m certifi
54
+ /usr/local/lib/python3.7/site-packages/certifi/cacert.pem
55
+
56
+ Enjoy!
57
+
58
+ .. _`Requests`: https://requests.readthedocs.io/en/master/
59
+
60
+ Addition/Removal of Certificates
61
+ --------------------------------
62
+
63
+ Certifi does not support any addition/removal or other modification of the
64
+ CA trust store content. This project is intended to provide a reliable and
65
+ highly portable root of trust to python deployments. Look to upstream projects
66
+ for methods to use alternate trust.
shared/package-files/d6/d67a78c1e3af987148e25d1b6ce379c71492abe98f24ec85ed0e69409a5e676f/debugger.py ADDED
@@ -0,0 +1,1120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Pdb debugger class.
4
+
5
+
6
+ This is an extension to PDB which adds a number of new features.
7
+ Note that there is also the `IPython.terminal.debugger` class which provides UI
8
+ improvements.
9
+
10
+ We also strongly recommend to use this via the `ipdb` package, which provides
11
+ extra configuration options.
12
+
13
+ Among other things, this subclass of PDB:
14
+ - supports many IPython magics like pdef/psource
15
+ - hide frames in tracebacks based on `__tracebackhide__`
16
+ - allows to skip frames based on `__debuggerskip__`
17
+
18
+ The skipping and hiding frames are configurable via the `skip_predicates`
19
+ command.
20
+
21
+ By default, frames from readonly files will be hidden, frames containing
22
+ ``__tracebackhide__=True`` will be hidden.
23
+
24
+ Frames containing ``__debuggerskip__`` will be stepped over, frames who's parent
25
+ frames value of ``__debuggerskip__`` is ``True`` will be skipped.
26
+
27
+ >>> def helpers_helper():
28
+ ... pass
29
+ ...
30
+ ... def helper_1():
31
+ ... print("don't step in me")
32
+ ... helpers_helpers() # will be stepped over unless breakpoint set.
33
+ ...
34
+ ...
35
+ ... def helper_2():
36
+ ... print("in me neither")
37
+ ...
38
+
39
+ One can define a decorator that wraps a function between the two helpers:
40
+
41
+ >>> def pdb_skipped_decorator(function):
42
+ ...
43
+ ...
44
+ ... def wrapped_fn(*args, **kwargs):
45
+ ... __debuggerskip__ = True
46
+ ... helper_1()
47
+ ... __debuggerskip__ = False
48
+ ... result = function(*args, **kwargs)
49
+ ... __debuggerskip__ = True
50
+ ... helper_2()
51
+ ... # setting __debuggerskip__ to False again is not necessary
52
+ ... return result
53
+ ...
54
+ ... return wrapped_fn
55
+
56
+ When decorating a function, ipdb will directly step into ``bar()`` by
57
+ default:
58
+
59
+ >>> @foo_decorator
60
+ ... def bar(x, y):
61
+ ... return x * y
62
+
63
+
64
+ You can toggle the behavior with
65
+
66
+ ipdb> skip_predicates debuggerskip false
67
+
68
+ or configure it in your ``.pdbrc``
69
+
70
+
71
+
72
+ License
73
+ -------
74
+
75
+ Modified from the standard pdb.Pdb class to avoid including readline, so that
76
+ the command line completion of other programs which include this isn't
77
+ damaged.
78
+
79
+ In the future, this class will be expanded with improvements over the standard
80
+ pdb.
81
+
82
+ The original code in this file is mainly lifted out of cmd.py in Python 2.2,
83
+ with minor changes. Licensing should therefore be under the standard Python
84
+ terms. For details on the PSF (Python Software Foundation) standard license,
85
+ see:
86
+
87
+ https://docs.python.org/2/license.html
88
+
89
+
90
+ All the changes since then are under the same license as IPython.
91
+
92
+ """
93
+
94
+ #*****************************************************************************
95
+ #
96
+ # This file is licensed under the PSF license.
97
+ #
98
+ # Copyright (C) 2001 Python Software Foundation, www.python.org
99
+ # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
100
+ #
101
+ #
102
+ #*****************************************************************************
103
+
104
+ import inspect
105
+ import linecache
106
+ import sys
107
+ import re
108
+ import os
109
+
110
+ from IPython import get_ipython
111
+ from contextlib import contextmanager
112
+ from IPython.utils import PyColorize
113
+ from IPython.utils import coloransi, py3compat
114
+ from IPython.core.excolors import exception_colors
115
+
116
+ # skip module docstests
117
+ __skip_doctest__ = True
118
+
119
+ prompt = 'ipdb> '
120
+
121
+ # We have to check this directly from sys.argv, config struct not yet available
122
+ from pdb import Pdb as OldPdb
123
+
124
+ # Allow the set_trace code to operate outside of an ipython instance, even if
125
+ # it does so with some limitations. The rest of this support is implemented in
126
+ # the Tracer constructor.
127
+
128
+ DEBUGGERSKIP = "__debuggerskip__"
129
+
130
+
131
+ # this has been implemented in Pdb in Python 3.13 (https://github.com/python/cpython/pull/106676
132
+ # on lower python versions, we backported the feature.
133
+ CHAIN_EXCEPTIONS = sys.version_info < (3, 13)
134
+
135
+
136
+ def make_arrow(pad):
137
+ """generate the leading arrow in front of traceback or debugger"""
138
+ if pad >= 2:
139
+ return '-'*(pad-2) + '> '
140
+ elif pad == 1:
141
+ return '>'
142
+ return ''
143
+
144
+
145
+ def BdbQuit_excepthook(et, ev, tb, excepthook=None):
146
+ """Exception hook which handles `BdbQuit` exceptions.
147
+
148
+ All other exceptions are processed using the `excepthook`
149
+ parameter.
150
+ """
151
+ raise ValueError(
152
+ "`BdbQuit_excepthook` is deprecated since version 5.1",
153
+ )
154
+
155
+
156
+ def BdbQuit_IPython_excepthook(self, et, ev, tb, tb_offset=None):
157
+ raise ValueError(
158
+ "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
159
+ DeprecationWarning, stacklevel=2)
160
+
161
+
162
+ RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
163
+
164
+
165
+ def strip_indentation(multiline_string):
166
+ return RGX_EXTRA_INDENT.sub('', multiline_string)
167
+
168
+
169
+ def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
170
+ """Make new_fn have old_fn's doc string. This is particularly useful
171
+ for the ``do_...`` commands that hook into the help system.
172
+ Adapted from from a comp.lang.python posting
173
+ by Duncan Booth."""
174
+ def wrapper(*args, **kw):
175
+ return new_fn(*args, **kw)
176
+ if old_fn.__doc__:
177
+ wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
178
+ return wrapper
179
+
180
+
181
+ class Pdb(OldPdb):
182
+ """Modified Pdb class, does not load readline.
183
+
184
+ for a standalone version that uses prompt_toolkit, see
185
+ `IPython.terminal.debugger.TerminalPdb` and
186
+ `IPython.terminal.debugger.set_trace()`
187
+
188
+
189
+ This debugger can hide and skip frames that are tagged according to some predicates.
190
+ See the `skip_predicates` commands.
191
+
192
+ """
193
+
194
+ if CHAIN_EXCEPTIONS:
195
+ MAX_CHAINED_EXCEPTION_DEPTH = 999
196
+
197
+ default_predicates = {
198
+ "tbhide": True,
199
+ "readonly": False,
200
+ "ipython_internal": True,
201
+ "debuggerskip": True,
202
+ }
203
+
204
+ def __init__(self, completekey=None, stdin=None, stdout=None, context=5, **kwargs):
205
+ """Create a new IPython debugger.
206
+
207
+ Parameters
208
+ ----------
209
+ completekey : default None
210
+ Passed to pdb.Pdb.
211
+ stdin : default None
212
+ Passed to pdb.Pdb.
213
+ stdout : default None
214
+ Passed to pdb.Pdb.
215
+ context : int
216
+ Number of lines of source code context to show when
217
+ displaying stacktrace information.
218
+ **kwargs
219
+ Passed to pdb.Pdb.
220
+
221
+ Notes
222
+ -----
223
+ The possibilities are python version dependent, see the python
224
+ docs for more info.
225
+ """
226
+
227
+ # Parent constructor:
228
+ try:
229
+ self.context = int(context)
230
+ if self.context <= 0:
231
+ raise ValueError("Context must be a positive integer")
232
+ except (TypeError, ValueError) as e:
233
+ raise ValueError("Context must be a positive integer") from e
234
+
235
+ # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
236
+ OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
237
+
238
+ # IPython changes...
239
+ self.shell = get_ipython()
240
+
241
+ if self.shell is None:
242
+ save_main = sys.modules['__main__']
243
+ # No IPython instance running, we must create one
244
+ from IPython.terminal.interactiveshell import \
245
+ TerminalInteractiveShell
246
+ self.shell = TerminalInteractiveShell.instance()
247
+ # needed by any code which calls __import__("__main__") after
248
+ # the debugger was entered. See also #9941.
249
+ sys.modules["__main__"] = save_main
250
+
251
+
252
+ color_scheme = self.shell.colors
253
+
254
+ self.aliases = {}
255
+
256
+ # Create color table: we copy the default one from the traceback
257
+ # module and add a few attributes needed for debugging
258
+ self.color_scheme_table = exception_colors()
259
+
260
+ # shorthands
261
+ C = coloransi.TermColors
262
+ cst = self.color_scheme_table
263
+
264
+ cst['NoColor'].colors.prompt = C.NoColor
265
+ cst['NoColor'].colors.breakpoint_enabled = C.NoColor
266
+ cst['NoColor'].colors.breakpoint_disabled = C.NoColor
267
+
268
+ cst['Linux'].colors.prompt = C.Green
269
+ cst['Linux'].colors.breakpoint_enabled = C.LightRed
270
+ cst['Linux'].colors.breakpoint_disabled = C.Red
271
+
272
+ cst['LightBG'].colors.prompt = C.Blue
273
+ cst['LightBG'].colors.breakpoint_enabled = C.LightRed
274
+ cst['LightBG'].colors.breakpoint_disabled = C.Red
275
+
276
+ cst['Neutral'].colors.prompt = C.Blue
277
+ cst['Neutral'].colors.breakpoint_enabled = C.LightRed
278
+ cst['Neutral'].colors.breakpoint_disabled = C.Red
279
+
280
+ # Add a python parser so we can syntax highlight source while
281
+ # debugging.
282
+ self.parser = PyColorize.Parser(style=color_scheme)
283
+ self.set_colors(color_scheme)
284
+
285
+ # Set the prompt - the default prompt is '(Pdb)'
286
+ self.prompt = prompt
287
+ self.skip_hidden = True
288
+ self.report_skipped = True
289
+
290
+ # list of predicates we use to skip frames
291
+ self._predicates = self.default_predicates
292
+
293
+ if CHAIN_EXCEPTIONS:
294
+ self._chained_exceptions = tuple()
295
+ self._chained_exception_index = 0
296
+
297
+ #
298
+ def set_colors(self, scheme):
299
+ """Shorthand access to the color table scheme selector method."""
300
+ self.color_scheme_table.set_active_scheme(scheme)
301
+ self.parser.style = scheme
302
+
303
+ def set_trace(self, frame=None):
304
+ if frame is None:
305
+ frame = sys._getframe().f_back
306
+ self.initial_frame = frame
307
+ return super().set_trace(frame)
308
+
309
+ def _hidden_predicate(self, frame):
310
+ """
311
+ Given a frame return whether it it should be hidden or not by IPython.
312
+ """
313
+
314
+ if self._predicates["readonly"]:
315
+ fname = frame.f_code.co_filename
316
+ # we need to check for file existence and interactively define
317
+ # function would otherwise appear as RO.
318
+ if os.path.isfile(fname) and not os.access(fname, os.W_OK):
319
+ return True
320
+
321
+ if self._predicates["tbhide"]:
322
+ if frame in (self.curframe, getattr(self, "initial_frame", None)):
323
+ return False
324
+ frame_locals = self._get_frame_locals(frame)
325
+ if "__tracebackhide__" not in frame_locals:
326
+ return False
327
+ return frame_locals["__tracebackhide__"]
328
+ return False
329
+
330
+ def hidden_frames(self, stack):
331
+ """
332
+ Given an index in the stack return whether it should be skipped.
333
+
334
+ This is used in up/down and where to skip frames.
335
+ """
336
+ # The f_locals dictionary is updated from the actual frame
337
+ # locals whenever the .f_locals accessor is called, so we
338
+ # avoid calling it here to preserve self.curframe_locals.
339
+ # Furthermore, there is no good reason to hide the current frame.
340
+ ip_hide = [self._hidden_predicate(s[0]) for s in stack]
341
+ ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
342
+ if ip_start and self._predicates["ipython_internal"]:
343
+ ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
344
+ return ip_hide
345
+
346
+ if CHAIN_EXCEPTIONS:
347
+
348
+ def _get_tb_and_exceptions(self, tb_or_exc):
349
+ """
350
+ Given a tracecack or an exception, return a tuple of chained exceptions
351
+ and current traceback to inspect.
352
+ This will deal with selecting the right ``__cause__`` or ``__context__``
353
+ as well as handling cycles, and return a flattened list of exceptions we
354
+ can jump to with do_exceptions.
355
+ """
356
+ _exceptions = []
357
+ if isinstance(tb_or_exc, BaseException):
358
+ traceback, current = tb_or_exc.__traceback__, tb_or_exc
359
+
360
+ while current is not None:
361
+ if current in _exceptions:
362
+ break
363
+ _exceptions.append(current)
364
+ if current.__cause__ is not None:
365
+ current = current.__cause__
366
+ elif (
367
+ current.__context__ is not None
368
+ and not current.__suppress_context__
369
+ ):
370
+ current = current.__context__
371
+
372
+ if len(_exceptions) >= self.MAX_CHAINED_EXCEPTION_DEPTH:
373
+ self.message(
374
+ f"More than {self.MAX_CHAINED_EXCEPTION_DEPTH}"
375
+ " chained exceptions found, not all exceptions"
376
+ "will be browsable with `exceptions`."
377
+ )
378
+ break
379
+ else:
380
+ traceback = tb_or_exc
381
+ return tuple(reversed(_exceptions)), traceback
382
+
383
+ @contextmanager
384
+ def _hold_exceptions(self, exceptions):
385
+ """
386
+ Context manager to ensure proper cleaning of exceptions references
387
+ When given a chained exception instead of a traceback,
388
+ pdb may hold references to many objects which may leak memory.
389
+ We use this context manager to make sure everything is properly cleaned
390
+ """
391
+ try:
392
+ self._chained_exceptions = exceptions
393
+ self._chained_exception_index = len(exceptions) - 1
394
+ yield
395
+ finally:
396
+ # we can't put those in forget as otherwise they would
397
+ # be cleared on exception change
398
+ self._chained_exceptions = tuple()
399
+ self._chained_exception_index = 0
400
+
401
+ def do_exceptions(self, arg):
402
+ """exceptions [number]
403
+ List or change current exception in an exception chain.
404
+ Without arguments, list all the current exception in the exception
405
+ chain. Exceptions will be numbered, with the current exception indicated
406
+ with an arrow.
407
+ If given an integer as argument, switch to the exception at that index.
408
+ """
409
+ if not self._chained_exceptions:
410
+ self.message(
411
+ "Did not find chained exceptions. To move between"
412
+ " exceptions, pdb/post_mortem must be given an exception"
413
+ " object rather than a traceback."
414
+ )
415
+ return
416
+ if not arg:
417
+ for ix, exc in enumerate(self._chained_exceptions):
418
+ prompt = ">" if ix == self._chained_exception_index else " "
419
+ rep = repr(exc)
420
+ if len(rep) > 80:
421
+ rep = rep[:77] + "..."
422
+ indicator = (
423
+ " -"
424
+ if self._chained_exceptions[ix].__traceback__ is None
425
+ else f"{ix:>3}"
426
+ )
427
+ self.message(f"{prompt} {indicator} {rep}")
428
+ else:
429
+ try:
430
+ number = int(arg)
431
+ except ValueError:
432
+ self.error("Argument must be an integer")
433
+ return
434
+ if 0 <= number < len(self._chained_exceptions):
435
+ if self._chained_exceptions[number].__traceback__ is None:
436
+ self.error(
437
+ "This exception does not have a traceback, cannot jump to it"
438
+ )
439
+ return
440
+
441
+ self._chained_exception_index = number
442
+ self.setup(None, self._chained_exceptions[number].__traceback__)
443
+ self.print_stack_entry(self.stack[self.curindex])
444
+ else:
445
+ self.error("No exception with that number")
446
+
447
+ def interaction(self, frame, tb_or_exc):
448
+ try:
449
+ if CHAIN_EXCEPTIONS:
450
+ # this context manager is part of interaction in 3.13
451
+ _chained_exceptions, tb = self._get_tb_and_exceptions(tb_or_exc)
452
+ if isinstance(tb_or_exc, BaseException):
453
+ assert tb is not None, "main exception must have a traceback"
454
+ with self._hold_exceptions(_chained_exceptions):
455
+ OldPdb.interaction(self, frame, tb)
456
+ else:
457
+ OldPdb.interaction(self, frame, tb_or_exc)
458
+
459
+ except KeyboardInterrupt:
460
+ self.stdout.write("\n" + self.shell.get_exception_only())
461
+
462
+ def precmd(self, line):
463
+ """Perform useful escapes on the command before it is executed."""
464
+
465
+ if line.endswith("??"):
466
+ line = "pinfo2 " + line[:-2]
467
+ elif line.endswith("?"):
468
+ line = "pinfo " + line[:-1]
469
+
470
+ line = super().precmd(line)
471
+
472
+ return line
473
+
474
+ def new_do_frame(self, arg):
475
+ OldPdb.do_frame(self, arg)
476
+
477
+ def new_do_quit(self, arg):
478
+
479
+ if hasattr(self, 'old_all_completions'):
480
+ self.shell.Completer.all_completions = self.old_all_completions
481
+
482
+ return OldPdb.do_quit(self, arg)
483
+
484
+ do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
485
+
486
+ def new_do_restart(self, arg):
487
+ """Restart command. In the context of ipython this is exactly the same
488
+ thing as 'quit'."""
489
+ self.msg("Restart doesn't make sense here. Using 'quit' instead.")
490
+ return self.do_quit(arg)
491
+
492
+ def print_stack_trace(self, context=None):
493
+ Colors = self.color_scheme_table.active_colors
494
+ ColorsNormal = Colors.Normal
495
+ if context is None:
496
+ context = self.context
497
+ try:
498
+ context = int(context)
499
+ if context <= 0:
500
+ raise ValueError("Context must be a positive integer")
501
+ except (TypeError, ValueError) as e:
502
+ raise ValueError("Context must be a positive integer") from e
503
+ try:
504
+ skipped = 0
505
+ for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
506
+ if hidden and self.skip_hidden:
507
+ skipped += 1
508
+ continue
509
+ if skipped:
510
+ print(
511
+ f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
512
+ )
513
+ skipped = 0
514
+ self.print_stack_entry(frame_lineno, context=context)
515
+ if skipped:
516
+ print(
517
+ f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
518
+ )
519
+ except KeyboardInterrupt:
520
+ pass
521
+
522
+ def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
523
+ context=None):
524
+ if context is None:
525
+ context = self.context
526
+ try:
527
+ context = int(context)
528
+ if context <= 0:
529
+ raise ValueError("Context must be a positive integer")
530
+ except (TypeError, ValueError) as e:
531
+ raise ValueError("Context must be a positive integer") from e
532
+ print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
533
+
534
+ # vds: >>
535
+ frame, lineno = frame_lineno
536
+ filename = frame.f_code.co_filename
537
+ self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
538
+ # vds: <<
539
+
540
+ def _get_frame_locals(self, frame):
541
+ """ "
542
+ Accessing f_local of current frame reset the namespace, so we want to avoid
543
+ that or the following can happen
544
+
545
+ ipdb> foo
546
+ "old"
547
+ ipdb> foo = "new"
548
+ ipdb> foo
549
+ "new"
550
+ ipdb> where
551
+ ipdb> foo
552
+ "old"
553
+
554
+ So if frame is self.current_frame we instead return self.curframe_locals
555
+
556
+ """
557
+ if frame is self.curframe:
558
+ return self.curframe_locals
559
+ else:
560
+ return frame.f_locals
561
+
562
+ def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
563
+ if context is None:
564
+ context = self.context
565
+ try:
566
+ context = int(context)
567
+ if context <= 0:
568
+ print("Context must be a positive integer", file=self.stdout)
569
+ except (TypeError, ValueError):
570
+ print("Context must be a positive integer", file=self.stdout)
571
+
572
+ import reprlib
573
+
574
+ ret = []
575
+
576
+ Colors = self.color_scheme_table.active_colors
577
+ ColorsNormal = Colors.Normal
578
+ tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
579
+ tpl_call = "%s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal)
580
+ tpl_line = "%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
581
+ tpl_line_em = "%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
582
+
583
+ frame, lineno = frame_lineno
584
+
585
+ return_value = ''
586
+ loc_frame = self._get_frame_locals(frame)
587
+ if "__return__" in loc_frame:
588
+ rv = loc_frame["__return__"]
589
+ # return_value += '->'
590
+ return_value += reprlib.repr(rv) + "\n"
591
+ ret.append(return_value)
592
+
593
+ #s = filename + '(' + `lineno` + ')'
594
+ filename = self.canonic(frame.f_code.co_filename)
595
+ link = tpl_link % py3compat.cast_unicode(filename)
596
+
597
+ if frame.f_code.co_name:
598
+ func = frame.f_code.co_name
599
+ else:
600
+ func = "<lambda>"
601
+
602
+ call = ""
603
+ if func != "?":
604
+ if "__args__" in loc_frame:
605
+ args = reprlib.repr(loc_frame["__args__"])
606
+ else:
607
+ args = '()'
608
+ call = tpl_call % (func, args)
609
+
610
+ # The level info should be generated in the same format pdb uses, to
611
+ # avoid breaking the pdbtrack functionality of python-mode in *emacs.
612
+ if frame is self.curframe:
613
+ ret.append('> ')
614
+ else:
615
+ ret.append(" ")
616
+ ret.append("%s(%s)%s\n" % (link, lineno, call))
617
+
618
+ start = lineno - 1 - context//2
619
+ lines = linecache.getlines(filename)
620
+ start = min(start, len(lines) - context)
621
+ start = max(start, 0)
622
+ lines = lines[start : start + context]
623
+
624
+ for i, line in enumerate(lines):
625
+ show_arrow = start + 1 + i == lineno
626
+ linetpl = (frame is self.curframe or show_arrow) and tpl_line_em or tpl_line
627
+ ret.append(
628
+ self.__format_line(
629
+ linetpl, filename, start + 1 + i, line, arrow=show_arrow
630
+ )
631
+ )
632
+ return "".join(ret)
633
+
634
+ def __format_line(self, tpl_line, filename, lineno, line, arrow=False):
635
+ bp_mark = ""
636
+ bp_mark_color = ""
637
+
638
+ new_line, err = self.parser.format2(line, 'str')
639
+ if not err:
640
+ line = new_line
641
+
642
+ bp = None
643
+ if lineno in self.get_file_breaks(filename):
644
+ bps = self.get_breaks(filename, lineno)
645
+ bp = bps[-1]
646
+
647
+ if bp:
648
+ Colors = self.color_scheme_table.active_colors
649
+ bp_mark = str(bp.number)
650
+ bp_mark_color = Colors.breakpoint_enabled
651
+ if not bp.enabled:
652
+ bp_mark_color = Colors.breakpoint_disabled
653
+
654
+ numbers_width = 7
655
+ if arrow:
656
+ # This is the line with the error
657
+ pad = numbers_width - len(str(lineno)) - len(bp_mark)
658
+ num = '%s%s' % (make_arrow(pad), str(lineno))
659
+ else:
660
+ num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
661
+
662
+ return tpl_line % (bp_mark_color + bp_mark, num, line)
663
+
664
+ def print_list_lines(self, filename, first, last):
665
+ """The printing (as opposed to the parsing part of a 'list'
666
+ command."""
667
+ try:
668
+ Colors = self.color_scheme_table.active_colors
669
+ ColorsNormal = Colors.Normal
670
+ tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
671
+ tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
672
+ src = []
673
+ if filename == "<string>" and hasattr(self, "_exec_filename"):
674
+ filename = self._exec_filename
675
+
676
+ for lineno in range(first, last+1):
677
+ line = linecache.getline(filename, lineno)
678
+ if not line:
679
+ break
680
+
681
+ if lineno == self.curframe.f_lineno:
682
+ line = self.__format_line(
683
+ tpl_line_em, filename, lineno, line, arrow=True
684
+ )
685
+ else:
686
+ line = self.__format_line(
687
+ tpl_line, filename, lineno, line, arrow=False
688
+ )
689
+
690
+ src.append(line)
691
+ self.lineno = lineno
692
+
693
+ print(''.join(src), file=self.stdout)
694
+
695
+ except KeyboardInterrupt:
696
+ pass
697
+
698
+ def do_skip_predicates(self, args):
699
+ """
700
+ Turn on/off individual predicates as to whether a frame should be hidden/skip.
701
+
702
+ The global option to skip (or not) hidden frames is set with skip_hidden
703
+
704
+ To change the value of a predicate
705
+
706
+ skip_predicates key [true|false]
707
+
708
+ Call without arguments to see the current values.
709
+
710
+ To permanently change the value of an option add the corresponding
711
+ command to your ``~/.pdbrc`` file. If you are programmatically using the
712
+ Pdb instance you can also change the ``default_predicates`` class
713
+ attribute.
714
+ """
715
+ if not args.strip():
716
+ print("current predicates:")
717
+ for p, v in self._predicates.items():
718
+ print(" ", p, ":", v)
719
+ return
720
+ type_value = args.strip().split(" ")
721
+ if len(type_value) != 2:
722
+ print(
723
+ f"Usage: skip_predicates <type> <value>, with <type> one of {set(self._predicates.keys())}"
724
+ )
725
+ return
726
+
727
+ type_, value = type_value
728
+ if type_ not in self._predicates:
729
+ print(f"{type_!r} not in {set(self._predicates.keys())}")
730
+ return
731
+ if value.lower() not in ("true", "yes", "1", "no", "false", "0"):
732
+ print(
733
+ f"{value!r} is invalid - use one of ('true', 'yes', '1', 'no', 'false', '0')"
734
+ )
735
+ return
736
+
737
+ self._predicates[type_] = value.lower() in ("true", "yes", "1")
738
+ if not any(self._predicates.values()):
739
+ print(
740
+ "Warning, all predicates set to False, skip_hidden may not have any effects."
741
+ )
742
+
743
+ def do_skip_hidden(self, arg):
744
+ """
745
+ Change whether or not we should skip frames with the
746
+ __tracebackhide__ attribute.
747
+ """
748
+ if not arg.strip():
749
+ print(
750
+ f"skip_hidden = {self.skip_hidden}, use 'yes','no', 'true', or 'false' to change."
751
+ )
752
+ elif arg.strip().lower() in ("true", "yes"):
753
+ self.skip_hidden = True
754
+ elif arg.strip().lower() in ("false", "no"):
755
+ self.skip_hidden = False
756
+ if not any(self._predicates.values()):
757
+ print(
758
+ "Warning, all predicates set to False, skip_hidden may not have any effects."
759
+ )
760
+
761
+ def do_list(self, arg):
762
+ """Print lines of code from the current stack frame
763
+ """
764
+ self.lastcmd = 'list'
765
+ last = None
766
+ if arg and arg != ".":
767
+ try:
768
+ x = eval(arg, {}, {})
769
+ if type(x) == type(()):
770
+ first, last = x
771
+ first = int(first)
772
+ last = int(last)
773
+ if last < first:
774
+ # Assume it's a count
775
+ last = first + last
776
+ else:
777
+ first = max(1, int(x) - 5)
778
+ except:
779
+ print('*** Error in argument:', repr(arg), file=self.stdout)
780
+ return
781
+ elif self.lineno is None or arg == ".":
782
+ first = max(1, self.curframe.f_lineno - 5)
783
+ else:
784
+ first = self.lineno + 1
785
+ if last is None:
786
+ last = first + 10
787
+ self.print_list_lines(self.curframe.f_code.co_filename, first, last)
788
+
789
+ # vds: >>
790
+ lineno = first
791
+ filename = self.curframe.f_code.co_filename
792
+ self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
793
+ # vds: <<
794
+
795
+ do_l = do_list
796
+
797
+ def getsourcelines(self, obj):
798
+ lines, lineno = inspect.findsource(obj)
799
+ if inspect.isframe(obj) and obj.f_globals is self._get_frame_locals(obj):
800
+ # must be a module frame: do not try to cut a block out of it
801
+ return lines, 1
802
+ elif inspect.ismodule(obj):
803
+ return lines, 1
804
+ return inspect.getblock(lines[lineno:]), lineno+1
805
+
806
+ def do_longlist(self, arg):
807
+ """Print lines of code from the current stack frame.
808
+
809
+ Shows more lines than 'list' does.
810
+ """
811
+ self.lastcmd = 'longlist'
812
+ try:
813
+ lines, lineno = self.getsourcelines(self.curframe)
814
+ except OSError as err:
815
+ self.error(err)
816
+ return
817
+ last = lineno + len(lines)
818
+ self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
819
+ do_ll = do_longlist
820
+
821
+ def do_debug(self, arg):
822
+ """debug code
823
+ Enter a recursive debugger that steps through the code
824
+ argument (which is an arbitrary expression or statement to be
825
+ executed in the current environment).
826
+ """
827
+ trace_function = sys.gettrace()
828
+ sys.settrace(None)
829
+ globals = self.curframe.f_globals
830
+ locals = self.curframe_locals
831
+ p = self.__class__(completekey=self.completekey,
832
+ stdin=self.stdin, stdout=self.stdout)
833
+ p.use_rawinput = self.use_rawinput
834
+ p.prompt = "(%s) " % self.prompt.strip()
835
+ self.message("ENTERING RECURSIVE DEBUGGER")
836
+ sys.call_tracing(p.run, (arg, globals, locals))
837
+ self.message("LEAVING RECURSIVE DEBUGGER")
838
+ sys.settrace(trace_function)
839
+ self.lastcmd = p.lastcmd
840
+
841
+ def do_pdef(self, arg):
842
+ """Print the call signature for any callable object.
843
+
844
+ The debugger interface to %pdef"""
845
+ namespaces = [
846
+ ("Locals", self.curframe_locals),
847
+ ("Globals", self.curframe.f_globals),
848
+ ]
849
+ self.shell.find_line_magic("pdef")(arg, namespaces=namespaces)
850
+
851
+ def do_pdoc(self, arg):
852
+ """Print the docstring for an object.
853
+
854
+ The debugger interface to %pdoc."""
855
+ namespaces = [
856
+ ("Locals", self.curframe_locals),
857
+ ("Globals", self.curframe.f_globals),
858
+ ]
859
+ self.shell.find_line_magic("pdoc")(arg, namespaces=namespaces)
860
+
861
+ def do_pfile(self, arg):
862
+ """Print (or run through pager) the file where an object is defined.
863
+
864
+ The debugger interface to %pfile.
865
+ """
866
+ namespaces = [
867
+ ("Locals", self.curframe_locals),
868
+ ("Globals", self.curframe.f_globals),
869
+ ]
870
+ self.shell.find_line_magic("pfile")(arg, namespaces=namespaces)
871
+
872
+ def do_pinfo(self, arg):
873
+ """Provide detailed information about an object.
874
+
875
+ The debugger interface to %pinfo, i.e., obj?."""
876
+ namespaces = [
877
+ ("Locals", self.curframe_locals),
878
+ ("Globals", self.curframe.f_globals),
879
+ ]
880
+ self.shell.find_line_magic("pinfo")(arg, namespaces=namespaces)
881
+
882
+ def do_pinfo2(self, arg):
883
+ """Provide extra detailed information about an object.
884
+
885
+ The debugger interface to %pinfo2, i.e., obj??."""
886
+ namespaces = [
887
+ ("Locals", self.curframe_locals),
888
+ ("Globals", self.curframe.f_globals),
889
+ ]
890
+ self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces)
891
+
892
+ def do_psource(self, arg):
893
+ """Print (or run through pager) the source code for an object."""
894
+ namespaces = [
895
+ ("Locals", self.curframe_locals),
896
+ ("Globals", self.curframe.f_globals),
897
+ ]
898
+ self.shell.find_line_magic("psource")(arg, namespaces=namespaces)
899
+
900
+ def do_where(self, arg):
901
+ """w(here)
902
+ Print a stack trace, with the most recent frame at the bottom.
903
+ An arrow indicates the "current frame", which determines the
904
+ context of most commands. 'bt' is an alias for this command.
905
+
906
+ Take a number as argument as an (optional) number of context line to
907
+ print"""
908
+ if arg:
909
+ try:
910
+ context = int(arg)
911
+ except ValueError as err:
912
+ self.error(err)
913
+ return
914
+ self.print_stack_trace(context)
915
+ else:
916
+ self.print_stack_trace()
917
+
918
+ do_w = do_where
919
+
920
+ def break_anywhere(self, frame):
921
+ """
922
+ _stop_in_decorator_internals is overly restrictive, as we may still want
923
+ to trace function calls, so we need to also update break_anywhere so
924
+ that is we don't `stop_here`, because of debugger skip, we may still
925
+ stop at any point inside the function
926
+
927
+ """
928
+
929
+ sup = super().break_anywhere(frame)
930
+ if sup:
931
+ return sup
932
+ if self._predicates["debuggerskip"]:
933
+ if DEBUGGERSKIP in frame.f_code.co_varnames:
934
+ return True
935
+ if frame.f_back and self._get_frame_locals(frame.f_back).get(DEBUGGERSKIP):
936
+ return True
937
+ return False
938
+
939
+ def _is_in_decorator_internal_and_should_skip(self, frame):
940
+ """
941
+ Utility to tell us whether we are in a decorator internal and should stop.
942
+
943
+ """
944
+
945
+ # if we are disabled don't skip
946
+ if not self._predicates["debuggerskip"]:
947
+ return False
948
+
949
+ # if frame is tagged, skip by default.
950
+ if DEBUGGERSKIP in frame.f_code.co_varnames:
951
+ return True
952
+
953
+ # if one of the parent frame value set to True skip as well.
954
+
955
+ cframe = frame
956
+ while getattr(cframe, "f_back", None):
957
+ cframe = cframe.f_back
958
+ if self._get_frame_locals(cframe).get(DEBUGGERSKIP):
959
+ return True
960
+
961
+ return False
962
+
963
+ def stop_here(self, frame):
964
+ if self._is_in_decorator_internal_and_should_skip(frame) is True:
965
+ return False
966
+
967
+ hidden = False
968
+ if self.skip_hidden:
969
+ hidden = self._hidden_predicate(frame)
970
+ if hidden:
971
+ if self.report_skipped:
972
+ Colors = self.color_scheme_table.active_colors
973
+ ColorsNormal = Colors.Normal
974
+ print(
975
+ f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n"
976
+ )
977
+ return super().stop_here(frame)
978
+
979
+ def do_up(self, arg):
980
+ """u(p) [count]
981
+ Move the current frame count (default one) levels up in the
982
+ stack trace (to an older frame).
983
+
984
+ Will skip hidden frames.
985
+ """
986
+ # modified version of upstream that skips
987
+ # frames with __tracebackhide__
988
+ if self.curindex == 0:
989
+ self.error("Oldest frame")
990
+ return
991
+ try:
992
+ count = int(arg or 1)
993
+ except ValueError:
994
+ self.error("Invalid frame count (%s)" % arg)
995
+ return
996
+ skipped = 0
997
+ if count < 0:
998
+ _newframe = 0
999
+ else:
1000
+ counter = 0
1001
+ hidden_frames = self.hidden_frames(self.stack)
1002
+ for i in range(self.curindex - 1, -1, -1):
1003
+ if hidden_frames[i] and self.skip_hidden:
1004
+ skipped += 1
1005
+ continue
1006
+ counter += 1
1007
+ if counter >= count:
1008
+ break
1009
+ else:
1010
+ # if no break occurred.
1011
+ self.error(
1012
+ "all frames above hidden, use `skip_hidden False` to get get into those."
1013
+ )
1014
+ return
1015
+
1016
+ Colors = self.color_scheme_table.active_colors
1017
+ ColorsNormal = Colors.Normal
1018
+ _newframe = i
1019
+ self._select_frame(_newframe)
1020
+ if skipped:
1021
+ print(
1022
+ f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
1023
+ )
1024
+
1025
+ def do_down(self, arg):
1026
+ """d(own) [count]
1027
+ Move the current frame count (default one) levels down in the
1028
+ stack trace (to a newer frame).
1029
+
1030
+ Will skip hidden frames.
1031
+ """
1032
+ if self.curindex + 1 == len(self.stack):
1033
+ self.error("Newest frame")
1034
+ return
1035
+ try:
1036
+ count = int(arg or 1)
1037
+ except ValueError:
1038
+ self.error("Invalid frame count (%s)" % arg)
1039
+ return
1040
+ if count < 0:
1041
+ _newframe = len(self.stack) - 1
1042
+ else:
1043
+ counter = 0
1044
+ skipped = 0
1045
+ hidden_frames = self.hidden_frames(self.stack)
1046
+ for i in range(self.curindex + 1, len(self.stack)):
1047
+ if hidden_frames[i] and self.skip_hidden:
1048
+ skipped += 1
1049
+ continue
1050
+ counter += 1
1051
+ if counter >= count:
1052
+ break
1053
+ else:
1054
+ self.error(
1055
+ "all frames below hidden, use `skip_hidden False` to get get into those."
1056
+ )
1057
+ return
1058
+
1059
+ Colors = self.color_scheme_table.active_colors
1060
+ ColorsNormal = Colors.Normal
1061
+ if skipped:
1062
+ print(
1063
+ f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
1064
+ )
1065
+ _newframe = i
1066
+
1067
+ self._select_frame(_newframe)
1068
+
1069
+ do_d = do_down
1070
+ do_u = do_up
1071
+
1072
+ def do_context(self, context):
1073
+ """context number_of_lines
1074
+ Set the number of lines of source code to show when displaying
1075
+ stacktrace information.
1076
+ """
1077
+ try:
1078
+ new_context = int(context)
1079
+ if new_context <= 0:
1080
+ raise ValueError()
1081
+ self.context = new_context
1082
+ except ValueError:
1083
+ self.error("The 'context' command requires a positive integer argument.")
1084
+
1085
+
1086
+ class InterruptiblePdb(Pdb):
1087
+ """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
1088
+
1089
+ def cmdloop(self, intro=None):
1090
+ """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
1091
+ try:
1092
+ return OldPdb.cmdloop(self, intro=intro)
1093
+ except KeyboardInterrupt:
1094
+ self.stop_here = lambda frame: False
1095
+ self.do_quit("")
1096
+ sys.settrace(None)
1097
+ self.quitting = False
1098
+ raise
1099
+
1100
+ def _cmdloop(self):
1101
+ while True:
1102
+ try:
1103
+ # keyboard interrupts allow for an easy way to cancel
1104
+ # the current command, so allow them during interactive input
1105
+ self.allow_kbdint = True
1106
+ self.cmdloop()
1107
+ self.allow_kbdint = False
1108
+ break
1109
+ except KeyboardInterrupt:
1110
+ self.message('--KeyboardInterrupt--')
1111
+ raise
1112
+
1113
+
1114
+ def set_trace(frame=None):
1115
+ """
1116
+ Start debugging from `frame`.
1117
+
1118
+ If frame is not specified, debugging starts from caller's frame.
1119
+ """
1120
+ Pdb().set_trace(frame or sys._getframe().f_back)
shared/package-files/d6/d67beab91315de97e2a7313f0dbefbc5003662256c864b256eb47a2896573769/application.pyi ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.mime.nonmultipart import MIMENonMultipart
2
+ from email.policy import Policy
3
+ from typing import Callable, Optional, Tuple, Union
4
+
5
+ _ParamsType = Union[str, None, Tuple[str, Optional[str], str]]
6
+
7
+ class MIMEApplication(MIMENonMultipart):
8
+ def __init__(
9
+ self,
10
+ _data: Union[str, bytes],
11
+ _subtype: str = ...,
12
+ _encoder: Callable[[MIMEApplication], None] = ...,
13
+ *,
14
+ policy: Optional[Policy] = ...,
15
+ **_params: _ParamsType,
16
+ ) -> None: ...
shared/package-files/d6/d67e1aed4c6de22de98b191f1150a1d1f8b3f04c4679a790fa4754cc5a780e5a/CUDADevice.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cuda/Exceptions.h>
4
+
5
+ #include <cuda.h>
6
+ #include <cuda_runtime.h>
7
+
8
+ namespace at::cuda {
9
+
10
+ inline Device getDeviceFromPtr(void* ptr) {
11
+ cudaPointerAttributes attr{};
12
+
13
+ AT_CUDA_CHECK(cudaPointerGetAttributes(&attr, ptr));
14
+
15
+ #if !defined(USE_ROCM)
16
+ TORCH_CHECK(attr.type != cudaMemoryTypeUnregistered,
17
+ "The specified pointer resides on host memory and is not registered with any CUDA device.");
18
+ #endif
19
+
20
+ return {c10::DeviceType::CUDA, static_cast<DeviceIndex>(attr.device)};
21
+ }
22
+
23
+ } // namespace at::cuda
shared/package-files/d6/d681474dbfb26dc4ea2d79b4af564e5607583131e51a836cf8f82fbb1e747771/Aqtobe ADDED
Binary file (997 Bytes). View file
 
shared/package-files/d6/d6816dd21d1187b267176ab0d50b53d17ce451a9d5f976fd5e2f41f597076880/chapel.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.lexers.chapel
3
+ ~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Lexer for the Chapel language.
6
+
7
+ :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pygments.lexer import RegexLexer, bygroups, words
12
+ from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
13
+ Number, Punctuation, Whitespace
14
+
15
+ __all__ = ['ChapelLexer']
16
+
17
+
18
+ class ChapelLexer(RegexLexer):
19
+ """
20
+ For Chapel source.
21
+
22
+ .. versionadded:: 2.0
23
+ """
24
+ name = 'Chapel'
25
+ url = 'https://chapel-lang.org/'
26
+ filenames = ['*.chpl']
27
+ aliases = ['chapel', 'chpl']
28
+ # mimetypes = ['text/x-chapel']
29
+
30
+ known_types = ('bool', 'bytes', 'complex', 'imag', 'int', 'locale',
31
+ 'nothing', 'opaque', 'range', 'real', 'string', 'uint',
32
+ 'void')
33
+
34
+ type_modifiers_par = ('atomic', 'single', 'sync')
35
+ type_modifiers_mem = ('borrowed', 'owned', 'shared', 'unmanaged')
36
+ type_modifiers = (*type_modifiers_par, *type_modifiers_mem)
37
+
38
+ declarations = ('config', 'const', 'in', 'inout', 'out', 'param', 'ref',
39
+ 'type', 'var')
40
+
41
+ constants = ('false', 'nil', 'none', 'true')
42
+
43
+ other_keywords = ('align', 'as',
44
+ 'begin', 'break', 'by',
45
+ 'catch', 'cobegin', 'coforall', 'continue',
46
+ 'defer', 'delete', 'dmapped', 'do', 'domain',
47
+ 'else', 'enum', 'except', 'export', 'extern',
48
+ 'for', 'forall', 'foreach', 'forwarding',
49
+ 'if', 'implements', 'import', 'index', 'init', 'inline',
50
+ 'label', 'lambda', 'let', 'lifetime', 'local',
51
+ 'new', 'noinit',
52
+ 'on', 'only', 'otherwise', 'override',
53
+ 'pragma', 'primitive', 'private', 'prototype', 'public',
54
+ 'reduce', 'require', 'return',
55
+ 'scan', 'select', 'serial', 'sparse', 'subdomain',
56
+ 'then', 'this', 'throw', 'throws', 'try',
57
+ 'use',
58
+ 'when', 'where', 'while', 'with',
59
+ 'yield',
60
+ 'zip')
61
+
62
+ tokens = {
63
+ 'root': [
64
+ (r'\n', Whitespace),
65
+ (r'\s+', Whitespace),
66
+ (r'\\\n', Text),
67
+
68
+ (r'//(.*?)\n', Comment.Single),
69
+ (r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
70
+
71
+ (words(declarations, suffix=r'\b'), Keyword.Declaration),
72
+ (words(constants, suffix=r'\b'), Keyword.Constant),
73
+ (words(known_types, suffix=r'\b'), Keyword.Type),
74
+ (words((*type_modifiers, *other_keywords), suffix=r'\b'), Keyword),
75
+
76
+ (r'@', Keyword, 'attributename'),
77
+ (r'(iter)(\s+)', bygroups(Keyword, Whitespace), 'procname'),
78
+ (r'(proc)(\s+)', bygroups(Keyword, Whitespace), 'procname'),
79
+ (r'(operator)(\s+)', bygroups(Keyword, Whitespace), 'procname'),
80
+ (r'(class|interface|module|record|union)(\s+)', bygroups(Keyword, Whitespace),
81
+ 'classname'),
82
+
83
+ # imaginary integers
84
+ (r'\d+i', Number),
85
+ (r'\d+\.\d*([Ee][-+]\d+)?i', Number),
86
+ (r'\.\d+([Ee][-+]\d+)?i', Number),
87
+ (r'\d+[Ee][-+]\d+i', Number),
88
+
89
+ # reals cannot end with a period due to lexical ambiguity with
90
+ # .. operator. See reference for rationale.
91
+ (r'(\d*\.\d+)([eE][+-]?[0-9]+)?i?', Number.Float),
92
+ (r'\d+[eE][+-]?[0-9]+i?', Number.Float),
93
+
94
+ # integer literals
95
+ # -- binary
96
+ (r'0[bB][01]+', Number.Bin),
97
+ # -- hex
98
+ (r'0[xX][0-9a-fA-F]+', Number.Hex),
99
+ # -- octal
100
+ (r'0[oO][0-7]+', Number.Oct),
101
+ # -- decimal
102
+ (r'[0-9]+', Number.Integer),
103
+
104
+ # strings
105
+ (r'"(\\\\|\\"|[^"])*"', String),
106
+ (r"'(\\\\|\\'|[^'])*'", String),
107
+
108
+ # tokens
109
+ (r'(=|\+=|-=|\*=|/=|\*\*=|%=|&=|\|=|\^=|&&=|\|\|=|<<=|>>=|'
110
+ r'<=>|<~>|\.\.|by|#|\.\.\.|'
111
+ r'&&|\|\||!|&|\||\^|~|<<|>>|'
112
+ r'==|!=|<=|>=|<|>|'
113
+ r'[+\-*/%]|\*\*)', Operator),
114
+ (r'[:;,.?()\[\]{}]', Punctuation),
115
+
116
+ # identifiers
117
+ (r'[a-zA-Z_][\w$]*', Name.Other),
118
+ ],
119
+ 'classname': [
120
+ (r'[a-zA-Z_][\w$]*', Name.Class, '#pop'),
121
+ ],
122
+ 'procname': [
123
+ (r'([a-zA-Z_][.\w$]*|' # regular function name, including secondary
124
+ r'\~[a-zA-Z_][.\w$]*|' # support for legacy destructors
125
+ r'[+*/!~%<>=&^|\-:]{1,2})', # operators
126
+ Name.Function, '#pop'),
127
+
128
+ # allow `proc (atomic T).foo`
129
+ (r'\(', Punctuation, "receivertype"),
130
+ (r'\)+\.', Punctuation),
131
+ ],
132
+ 'receivertype': [
133
+ (words(type_modifiers, suffix=r'\b'), Keyword),
134
+ (words(known_types, suffix=r'\b'), Keyword.Type),
135
+ (r'[^()]*', Name.Other, '#pop'),
136
+ ],
137
+ 'attributename': [
138
+ (r'[a-zA-Z_][.\w$]*', Name.Decorator, '#pop'),
139
+ ],
140
+ }
shared/package-files/d6/d6836634278d0962c758bf6fc73ab790bebb366b4e502f08afd98bafcd6951b1/dropout_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor dropout(const at::Tensor & input, double p, bool train);
21
+ TORCH_API at::Tensor & dropout_(at::Tensor & self, double p, bool train);
22
+
23
+ } // namespace compositeimplicitautograd
24
+ } // namespace at
shared/package-files/d6/d689ccaa33ffa701450012a45c024ca4bb2ca767826a361bfc399f7465bcf1d8/contentmanager.pyi ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.message import Message
2
+ from typing import Any, Callable
3
+
4
+ class ContentManager:
5
+ def __init__(self) -> None: ...
6
+ def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ...
7
+ def set_content(self, msg: Message, obj: Any, *args: Any, **kw: Any) -> Any: ...
8
+ def add_get_handler(self, key: str, handler: Callable[..., Any]) -> None: ...
9
+ def add_set_handler(self, typekey: type, handler: Callable[..., Any]) -> None: ...
10
+
11
+ raw_data_manager: ContentManager
shared/package-files/d6/d693b0d186a757968facc1b0aa401393c3935e6ea22c5da2b9460a6d47f56fa4/log_level.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+
10
+ def get_log_level() -> str:
11
+ """
12
+ Return default log level for pytorch.
13
+ """
14
+ return "WARNING"
shared/package-files/d6/d694d22b9954e8be40246e47df93d3210b47608a653288a96bb2a477f9bd1cd4/multipart.pyi ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from email.mime.base import MIMEBase
2
+
3
+ class MIMEMultipart(MIMEBase):
4
+ def __init__(self, _subtype=..., boundary=..., _subparts=..., **_params) -> None: ...
shared/package-files/d6/d694d6648579e11959bb8046b86028cb1ed9f50abcddc20127eaafe044c498a9/firstlinefinder.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module provides helper functions to find the first line of a function
3
+ body.
4
+ """
5
+
6
+ import ast
7
+ import inspect
8
+ import textwrap
9
+
10
+
11
+ class FindDefFirstLine(ast.NodeVisitor):
12
+ """
13
+ Attributes
14
+ ----------
15
+ first_stmt_line : int or None
16
+ This stores the first statement line number if the definition is found.
17
+ Or, ``None`` if the definition is not found.
18
+ """
19
+
20
+ def __init__(self, name, firstlineno):
21
+ """
22
+ Parameters
23
+ ----------
24
+ code :
25
+ The function's code object.
26
+ """
27
+ self._co_name = name
28
+ self._co_firstlineno = firstlineno
29
+ self.first_stmt_line = None
30
+
31
+ def _visit_children(self, node):
32
+ for child in ast.iter_child_nodes(node):
33
+ super().visit(child)
34
+
35
+ def visit_FunctionDef(self, node: ast.FunctionDef):
36
+ if node.name == self._co_name:
37
+ # Name of function matches.
38
+
39
+ # The `def` line may match co_firstlineno.
40
+ possible_start_lines = set([node.lineno])
41
+ if node.decorator_list:
42
+ # Has decorators.
43
+ # The first decorator line may match co_firstlineno.
44
+ first_decor = node.decorator_list[0]
45
+ possible_start_lines.add(first_decor.lineno)
46
+ # Does the first lineno match?
47
+ if self._co_firstlineno in possible_start_lines:
48
+ # Yes, we found the function.
49
+ # So, use the first statement line as the first line.
50
+ if node.body:
51
+ first_stmt = node.body[0]
52
+ if _is_docstring(first_stmt):
53
+ # Skip docstring
54
+ first_stmt = node.body[1]
55
+ self.first_stmt_line = first_stmt.lineno
56
+ return
57
+ else:
58
+ # This is probably unreachable.
59
+ # Function body cannot be bare. It must at least have
60
+ # A const string for docstring or a `pass`.
61
+ pass
62
+ self._visit_children(node)
63
+
64
+
65
+ def _is_docstring(node):
66
+ if isinstance(node, ast.Expr):
67
+ if (isinstance(node.value, ast.Constant)
68
+ and isinstance(node.value.value, str)):
69
+ return True
70
+ return False
71
+
72
+
73
+ def get_func_body_first_lineno(pyfunc):
74
+ """
75
+ Look up the first line of function body using the file in
76
+ ``pyfunc.__code__.co_filename``.
77
+
78
+ Returns
79
+ -------
80
+ lineno : int; or None
81
+ The first line number of the function body; or ``None`` if the first
82
+ line cannot be determined.
83
+ """
84
+ co = pyfunc.__code__
85
+ try:
86
+ with open(co.co_filename) as fin:
87
+ source = fin.read()
88
+ offset = 0
89
+ except (FileNotFoundError, OSError):
90
+ try:
91
+ lines, offset = inspect.getsourcelines(pyfunc)
92
+ source = "".join(lines)
93
+ offset = offset - 1
94
+ except (OSError, TypeError):
95
+ return None
96
+
97
+ tree = ast.parse(textwrap.dedent(source))
98
+ finder = FindDefFirstLine(co.co_name, co.co_firstlineno - offset)
99
+ finder.visit(tree)
100
+ if finder.first_stmt_line:
101
+ return finder.first_stmt_line + offset
102
+ else:
103
+ # No first line found.
104
+ return None
shared/package-files/d6/d696ba65b8f27cc5a1f9a634ef4564c007f587c9432b55db9387df6f3348b72e/transformPen.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.pens.filterPen import FilterPen, FilterPointPen
2
+
3
+ __all__ = ["TransformPen", "TransformPointPen"]
4
+
5
+
6
+ class TransformPen(FilterPen):
7
+ """Pen that transforms all coordinates using a Affine transformation,
8
+ and passes them to another pen.
9
+ """
10
+
11
+ def __init__(self, outPen, transformation):
12
+ """The 'outPen' argument is another pen object. It will receive the
13
+ transformed coordinates. The 'transformation' argument can either
14
+ be a six-tuple, or a fontTools.misc.transform.Transform object.
15
+ """
16
+ super(TransformPen, self).__init__(outPen)
17
+ if not hasattr(transformation, "transformPoint"):
18
+ from fontTools.misc.transform import Transform
19
+
20
+ transformation = Transform(*transformation)
21
+ self._transformation = transformation
22
+ self._transformPoint = transformation.transformPoint
23
+ self._stack = []
24
+
25
+ def moveTo(self, pt):
26
+ self._outPen.moveTo(self._transformPoint(pt))
27
+
28
+ def lineTo(self, pt):
29
+ self._outPen.lineTo(self._transformPoint(pt))
30
+
31
+ def curveTo(self, *points):
32
+ self._outPen.curveTo(*self._transformPoints(points))
33
+
34
+ def qCurveTo(self, *points):
35
+ if points[-1] is None:
36
+ points = self._transformPoints(points[:-1]) + [None]
37
+ else:
38
+ points = self._transformPoints(points)
39
+ self._outPen.qCurveTo(*points)
40
+
41
+ def _transformPoints(self, points):
42
+ transformPoint = self._transformPoint
43
+ return [transformPoint(pt) for pt in points]
44
+
45
+ def closePath(self):
46
+ self._outPen.closePath()
47
+
48
+ def endPath(self):
49
+ self._outPen.endPath()
50
+
51
+ def addComponent(self, glyphName, transformation):
52
+ transformation = self._transformation.transform(transformation)
53
+ self._outPen.addComponent(glyphName, transformation)
54
+
55
+
56
+ class TransformPointPen(FilterPointPen):
57
+ """PointPen that transforms all coordinates using a Affine transformation,
58
+ and passes them to another PointPen.
59
+
60
+ For example::
61
+
62
+ >>> from fontTools.pens.recordingPen import RecordingPointPen
63
+ >>> rec = RecordingPointPen()
64
+ >>> pen = TransformPointPen(rec, (2, 0, 0, 2, -10, 5))
65
+ >>> v = iter(rec.value)
66
+ >>> pen.beginPath(identifier="contour-0")
67
+ >>> next(v)
68
+ ('beginPath', (), {'identifier': 'contour-0'})
69
+
70
+ >>> pen.addPoint((100, 100), "line")
71
+ >>> next(v)
72
+ ('addPoint', ((190, 205), 'line', False, None), {})
73
+
74
+ >>> pen.endPath()
75
+ >>> next(v)
76
+ ('endPath', (), {})
77
+
78
+ >>> pen.addComponent("a", (1, 0, 0, 1, -10, 5), identifier="component-0")
79
+ >>> next(v)
80
+ ('addComponent', ('a', <Transform [2 0 0 2 -30 15]>), {'identifier': 'component-0'})
81
+ """
82
+
83
+ def __init__(self, outPointPen, transformation):
84
+ """The 'outPointPen' argument is another point pen object.
85
+ It will receive the transformed coordinates.
86
+ The 'transformation' argument can either be a six-tuple, or a
87
+ fontTools.misc.transform.Transform object.
88
+ """
89
+ super().__init__(outPointPen)
90
+ if not hasattr(transformation, "transformPoint"):
91
+ from fontTools.misc.transform import Transform
92
+
93
+ transformation = Transform(*transformation)
94
+ self._transformation = transformation
95
+ self._transformPoint = transformation.transformPoint
96
+
97
+ def addPoint(self, pt, segmentType=None, smooth=False, name=None, **kwargs):
98
+ self._outPen.addPoint(
99
+ self._transformPoint(pt), segmentType, smooth, name, **kwargs
100
+ )
101
+
102
+ def addComponent(self, baseGlyphName, transformation, **kwargs):
103
+ transformation = self._transformation.transform(transformation)
104
+ self._outPen.addComponent(baseGlyphName, transformation, **kwargs)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ from fontTools.pens.basePen import _TestPen
109
+
110
+ pen = TransformPen(_TestPen(None), (2, 0, 0.5, 2, -10, 0))
111
+ pen.moveTo((0, 0))
112
+ pen.lineTo((0, 100))
113
+ pen.curveTo((50, 75), (60, 50), (50, 25), (0, 0))
114
+ pen.closePath()