-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTinyHyperGraphSectionPipelineSolver.ts
More file actions
553 lines (491 loc) · 17.4 KB
/
TinyHyperGraphSectionPipelineSolver.ts
File metadata and controls
553 lines (491 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import type { SerializedHyperGraph } from "@tscircuit/hypergraph"
import { BasePipelineSolver } from "@tscircuit/solver-utils"
import type { GraphicsObject } from "graphics-debug"
import { loadSerializedHyperGraph } from "../compat/loadSerializedHyperGraph"
import type {
TinyHyperGraphProblem,
TinyHyperGraphSolution,
TinyHyperGraphSolverOptions,
TinyHyperGraphTopology,
} from "../core"
import { DEFAULT_NON_CENTER_COST_PER_MM, TinyHyperGraphSolver } from "../core"
import type { RegionId } from "../types"
import type { TinyHyperGraphSectionSolverOptions } from "./index"
import { getActiveSectionRouteIds, TinyHyperGraphSectionSolver } from "./index"
/**
* Candidate section families used by the automatic section-mask search.
*
* Examples:
* - `self-touch`: ports are included when they touch the single hottest region.
* - `onehop-all`: ports are included only when all of their incident regions are
* inside the hottest region plus its immediate neighbors.
* - `twohop-touch`: ports are included when they touch any region in the
* two-hop neighborhood around the hottest region.
*/
export type TinyHyperGraphSectionCandidateFamily =
| "self-touch"
| "onehop-all"
| "onehop-touch"
| "twohop-all"
| "twohop-touch"
type SectionMaskCandidate = {
/** Human-readable identifier used in logs, stats, and benchmark output. */
label: string
/** Candidate generation family that produced this section mask. */
family: TinyHyperGraphSectionCandidateFamily
/** Regions included in the candidate section before conversion to a port mask. */
regionIds: RegionId[]
/** Rule for deciding whether a port belongs in the section mask. */
portSelectionRule: "touches-selected-region" | "all-incident-regions-selected"
}
type AutomaticSectionSearchResult = {
portSectionMask: Int8Array
baselineMaxRegionCost: number
finalMaxRegionCost: number
generatedCandidateCount: number
candidateCount: number
duplicateCandidateCount: number
totalMs: number
baselineEvaluationMs: number
candidateEligibilityMs: number
candidateInitMs: number
candidateSolveMs: number
candidateReplayScoreMs: number
winningCandidateLabel?: string
winningCandidateFamily?: TinyHyperGraphSectionCandidateFamily
}
const DEFAULT_SOLVE_GRAPH_OPTIONS: TinyHyperGraphSolverOptions = {
NON_CENTER_COST_PER_MM: DEFAULT_NON_CENTER_COST_PER_MM,
RIP_THRESHOLD_RAMP_ATTEMPTS: 5,
}
const DEFAULT_SECTION_SOLVER_OPTIONS: TinyHyperGraphSectionSolverOptions = {
DISTANCE_TO_COST: 0.05,
NON_CENTER_COST_PER_MM: DEFAULT_NON_CENTER_COST_PER_MM,
RIP_THRESHOLD_RAMP_ATTEMPTS: 16,
RIP_CONGESTION_REGION_COST_FACTOR: 0.1,
MAX_ITERATIONS: 1e6,
MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6,
EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY,
}
const DEFAULT_CANDIDATE_FAMILIES: TinyHyperGraphSectionCandidateFamily[] = [
"self-touch",
"onehop-all",
"onehop-touch",
"twohop-all",
"twohop-touch",
]
const DEFAULT_MAX_HOT_REGIONS = 2
const IMPROVEMENT_EPSILON = 1e-9
const getMaxRegionCost = (solver: TinyHyperGraphSolver) =>
solver.state.regionIntersectionCaches.reduce(
(maxRegionCost, regionIntersectionCache) =>
Math.max(maxRegionCost, regionIntersectionCache.existingRegionCost),
0,
)
const getSerializedOutputMaxRegionCost = (
serializedHyperGraph: SerializedHyperGraph,
) => {
const replay = loadSerializedHyperGraph(serializedHyperGraph)
const replayedSolver = new TinyHyperGraphSectionSolver(
replay.topology,
replay.problem,
replay.solution,
)
return getMaxRegionCost(replayedSolver.baselineSolver)
}
const getAdjacentRegionIds = (
topology: TinyHyperGraphTopology,
seedRegionIds: RegionId[],
) => {
const adjacentRegionIds = new Set(seedRegionIds)
for (const seedRegionId of seedRegionIds) {
for (const portId of topology.regionIncidentPorts[seedRegionId] ?? []) {
for (const regionId of topology.incidentPortRegion[portId] ?? []) {
adjacentRegionIds.add(regionId)
}
}
}
return [...adjacentRegionIds]
}
const createPortSectionMaskForRegionIds = (
topology: TinyHyperGraphTopology,
regionIds: RegionId[],
portSelectionRule:
| "touches-selected-region"
| "all-incident-regions-selected",
) => {
const selectedRegionIds = new Set(regionIds)
return Int8Array.from({ length: topology.portCount }, (_, portId) => {
const incidentRegionIds = topology.incidentPortRegion[portId] ?? []
if (portSelectionRule === "touches-selected-region") {
return incidentRegionIds.some((regionId) =>
selectedRegionIds.has(regionId),
)
? 1
: 0
}
return incidentRegionIds.length > 0 &&
incidentRegionIds.every((regionId) => selectedRegionIds.has(regionId))
? 1
: 0
})
}
const createProblemWithPortSectionMask = (
problem: TinyHyperGraphProblem,
portSectionMask: Int8Array,
): TinyHyperGraphProblem => ({
routeCount: problem.routeCount,
portSectionMask,
routeMetadata: problem.routeMetadata,
routeStartPort: new Int32Array(problem.routeStartPort),
routeEndPort: new Int32Array(problem.routeEndPort),
routeNet: new Int32Array(problem.routeNet),
regionNetId: new Int32Array(problem.regionNetId),
})
const getSectionMaskCandidates = (
solvedSolver: TinyHyperGraphSolver,
topology: TinyHyperGraphTopology,
maxHotRegions: number,
candidateFamilies: TinyHyperGraphSectionCandidateFamily[],
): SectionMaskCandidate[] => {
const hotRegionIds = solvedSolver.state.regionIntersectionCaches
.map((regionIntersectionCache, regionId) => ({
regionId,
regionCost: regionIntersectionCache.existingRegionCost,
}))
.filter(({ regionCost }) => regionCost > 0)
.sort((left, right) => right.regionCost - left.regionCost)
.slice(0, maxHotRegions)
.map(({ regionId }) => regionId)
const candidates: SectionMaskCandidate[] = []
for (const hotRegionId of hotRegionIds) {
const oneHopRegionIds = getAdjacentRegionIds(topology, [hotRegionId])
const twoHopRegionIds = getAdjacentRegionIds(topology, oneHopRegionIds)
const candidateByFamily: Record<
TinyHyperGraphSectionCandidateFamily,
SectionMaskCandidate
> = {
"self-touch": {
label: `hot-${hotRegionId}-self-touch`,
family: "self-touch",
regionIds: [hotRegionId],
portSelectionRule: "touches-selected-region",
},
"onehop-all": {
label: `hot-${hotRegionId}-onehop-all`,
family: "onehop-all",
regionIds: oneHopRegionIds,
portSelectionRule: "all-incident-regions-selected",
},
"onehop-touch": {
label: `hot-${hotRegionId}-onehop-touch`,
family: "onehop-touch",
regionIds: oneHopRegionIds,
portSelectionRule: "touches-selected-region",
},
"twohop-all": {
label: `hot-${hotRegionId}-twohop-all`,
family: "twohop-all",
regionIds: twoHopRegionIds,
portSelectionRule: "all-incident-regions-selected",
},
"twohop-touch": {
label: `hot-${hotRegionId}-twohop-touch`,
family: "twohop-touch",
regionIds: twoHopRegionIds,
portSelectionRule: "touches-selected-region",
},
}
for (const family of candidateFamilies) {
candidates.push(candidateByFamily[family])
}
}
return candidates
}
const findBestAutomaticSectionMask = (
solvedSolver: TinyHyperGraphSolver,
topology: TinyHyperGraphTopology,
problem: TinyHyperGraphProblem,
solution: TinyHyperGraphSolution,
searchConfig: TinyHyperGraphSectionPipelineSearchConfig | undefined,
sectionSolverOptions: TinyHyperGraphSectionSolverOptions,
): AutomaticSectionSearchResult => {
const searchStartTime = performance.now()
const baselineEvaluationStartTime = performance.now()
const baselineSectionSolver = new TinyHyperGraphSectionSolver(
topology,
problem,
solution,
sectionSolverOptions,
)
const baselineMaxRegionCost = getMaxRegionCost(
baselineSectionSolver.baselineSolver,
)
const baselineEvaluationMs = performance.now() - baselineEvaluationStartTime
let bestFinalMaxRegionCost = baselineMaxRegionCost
let bestPortSectionMask = new Int8Array(topology.portCount)
let winningCandidateLabel: string | undefined
let winningCandidateFamily: TinyHyperGraphSectionCandidateFamily | undefined
let generatedCandidateCount = 0
let candidateCount = 0
let duplicateCandidateCount = 0
let candidateEligibilityMs = 0
let candidateInitMs = 0
let candidateSolveMs = 0
let candidateReplayScoreMs = 0
const seenPortSectionMasks = new Set<string>()
const maxHotRegions =
searchConfig?.maxHotRegions ??
sectionSolverOptions.MAX_HOT_REGIONS ??
DEFAULT_MAX_HOT_REGIONS
for (const candidate of getSectionMaskCandidates(
solvedSolver,
topology,
maxHotRegions,
searchConfig?.candidateFamilies ?? DEFAULT_CANDIDATE_FAMILIES,
)) {
const candidateProblem = createProblemWithPortSectionMask(
problem,
createPortSectionMaskForRegionIds(
topology,
candidate.regionIds,
candidate.portSelectionRule,
),
)
generatedCandidateCount += 1
const portSectionMaskKey = candidateProblem.portSectionMask.join(",")
if (seenPortSectionMasks.has(portSectionMaskKey)) {
duplicateCandidateCount += 1
continue
}
seenPortSectionMasks.add(portSectionMaskKey)
try {
const eligibilityStartTime = performance.now()
const activeRouteIds = getActiveSectionRouteIds(
topology,
candidateProblem,
solution,
)
candidateEligibilityMs += performance.now() - eligibilityStartTime
if (activeRouteIds.length === 0) {
continue
}
candidateCount += 1
const candidateInitStartTime = performance.now()
const sectionSolver = new TinyHyperGraphSectionSolver(
topology,
candidateProblem,
solution,
sectionSolverOptions,
)
candidateInitMs += performance.now() - candidateInitStartTime
const candidateSolveStartTime = performance.now()
sectionSolver.solve()
candidateSolveMs += performance.now() - candidateSolveStartTime
if (sectionSolver.failed || !sectionSolver.solved) {
continue
}
const finalMaxRegionCost = Number(
sectionSolver.stats.finalMaxRegionCost ??
getMaxRegionCost(sectionSolver.getSolvedSolver()),
)
if (finalMaxRegionCost < bestFinalMaxRegionCost - IMPROVEMENT_EPSILON) {
const candidateReplayScoreStartTime = performance.now()
const replayedFinalMaxRegionCost = getSerializedOutputMaxRegionCost(
sectionSolver.getOutput(),
)
candidateReplayScoreMs +=
performance.now() - candidateReplayScoreStartTime
if (
replayedFinalMaxRegionCost <
bestFinalMaxRegionCost - IMPROVEMENT_EPSILON
) {
bestFinalMaxRegionCost = replayedFinalMaxRegionCost
bestPortSectionMask = new Int8Array(candidateProblem.portSectionMask)
winningCandidateLabel = candidate.label
winningCandidateFamily = candidate.family
}
}
} catch {
// Skip invalid section masks that split a route into multiple spans.
}
}
return {
portSectionMask: bestPortSectionMask,
baselineMaxRegionCost,
finalMaxRegionCost: bestFinalMaxRegionCost,
generatedCandidateCount,
candidateCount,
duplicateCandidateCount,
totalMs: performance.now() - searchStartTime,
baselineEvaluationMs,
candidateEligibilityMs,
candidateInitMs,
candidateSolveMs,
candidateReplayScoreMs,
winningCandidateLabel,
winningCandidateFamily,
}
}
export interface TinyHyperGraphSectionMaskContext {
serializedHyperGraph: SerializedHyperGraph
solvedSerializedHyperGraph: SerializedHyperGraph
solvedSolver: TinyHyperGraphSolver
topology: TinyHyperGraphTopology
problem: TinyHyperGraphProblem
solution: TinyHyperGraphSolution
}
export interface TinyHyperGraphSectionPipelineSearchConfig {
maxHotRegions?: number
candidateFamilies?: TinyHyperGraphSectionCandidateFamily[]
}
export interface TinyHyperGraphSectionPipelineInput {
serializedHyperGraph: SerializedHyperGraph
createSectionMask?: (context: TinyHyperGraphSectionMaskContext) => Int8Array
solveGraphOptions?: TinyHyperGraphSolverOptions
sectionSolverOptions?: TinyHyperGraphSectionSolverOptions
sectionSearchConfig?: TinyHyperGraphSectionPipelineSearchConfig
}
export class TinyHyperGraphSectionPipelineSolver extends BasePipelineSolver<TinyHyperGraphSectionPipelineInput> {
initialVisualizationSolver?: TinyHyperGraphSolver
selectedSectionMask?: Int8Array
selectedSectionCandidateLabel?: string
selectedSectionCandidateFamily?: TinyHyperGraphSectionCandidateFamily
override pipelineDef = [
{
solverName: "solveGraph",
solverClass: TinyHyperGraphSolver,
getConstructorParams: (instance: TinyHyperGraphSectionPipelineSolver) => {
const { topology, problem } = loadSerializedHyperGraph(
instance.inputProblem.serializedHyperGraph,
)
return [
topology,
problem,
{
...DEFAULT_SOLVE_GRAPH_OPTIONS,
...instance.inputProblem.solveGraphOptions,
},
] as ConstructorParameters<typeof TinyHyperGraphSolver>
},
},
{
solverName: "optimizeSection",
solverClass: TinyHyperGraphSectionSolver,
getConstructorParams: (instance: TinyHyperGraphSectionPipelineSolver) =>
instance.getSectionStageParams(),
},
]
getSectionStageParams(): [
TinyHyperGraphTopology,
TinyHyperGraphProblem,
TinyHyperGraphSolution,
TinyHyperGraphSectionSolverOptions,
] {
const solvedSerializedHyperGraph =
this.getStageOutput<SerializedHyperGraph>("solveGraph")
if (!solvedSerializedHyperGraph) {
throw new Error(
"solveGraph did not produce a solved serialized hypergraph",
)
}
const solvedSolver = this.getSolver<TinyHyperGraphSolver>("solveGraph")
if (!solvedSolver) {
throw new Error("solveGraph solver is unavailable")
}
const sectionSolverOptions = {
...DEFAULT_SECTION_SOLVER_OPTIONS,
...this.inputProblem.sectionSolverOptions,
}
const { topology, problem, solution } = loadSerializedHyperGraph(
solvedSerializedHyperGraph,
)
const portSectionMask = this.inputProblem.createSectionMask
? this.inputProblem.createSectionMask({
serializedHyperGraph: this.inputProblem.serializedHyperGraph,
solvedSerializedHyperGraph,
solvedSolver,
topology,
problem,
solution,
})
: (() => {
const searchResult = findBestAutomaticSectionMask(
solvedSolver,
topology,
problem,
solution,
this.inputProblem.sectionSearchConfig,
sectionSolverOptions,
)
this.selectedSectionCandidateLabel =
searchResult.winningCandidateLabel
this.selectedSectionCandidateFamily =
searchResult.winningCandidateFamily
this.stats = {
...this.stats,
sectionSearchGeneratedCandidateCount:
searchResult.generatedCandidateCount,
sectionSearchCandidateCount: searchResult.candidateCount,
sectionSearchDuplicateCandidateCount:
searchResult.duplicateCandidateCount,
sectionSearchBaselineMaxRegionCost:
searchResult.baselineMaxRegionCost,
sectionSearchFinalMaxRegionCost: searchResult.finalMaxRegionCost,
sectionSearchDelta:
searchResult.baselineMaxRegionCost -
searchResult.finalMaxRegionCost,
selectedSectionCandidateLabel:
searchResult.winningCandidateLabel ?? null,
selectedSectionCandidateFamily:
searchResult.winningCandidateFamily ?? null,
sectionSearchMs: searchResult.totalMs,
sectionSearchBaselineEvaluationMs:
searchResult.baselineEvaluationMs,
sectionSearchCandidateEligibilityMs:
searchResult.candidateEligibilityMs,
sectionSearchCandidateInitMs: searchResult.candidateInitMs,
sectionSearchCandidateSolveMs: searchResult.candidateSolveMs,
sectionSearchCandidateReplayScoreMs:
searchResult.candidateReplayScoreMs,
}
return searchResult.portSectionMask
})()
this.selectedSectionMask = new Int8Array(portSectionMask)
problem.portSectionMask = new Int8Array(portSectionMask)
this.stats = {
...this.stats,
sectionMaskPortCount: [...portSectionMask].filter((value) => value === 1)
.length,
}
return [topology, problem, solution, sectionSolverOptions]
}
getInitialVisualizationSolver() {
if (!this.initialVisualizationSolver) {
const { topology, problem } = loadSerializedHyperGraph(
this.inputProblem.serializedHyperGraph,
)
this.initialVisualizationSolver = new TinyHyperGraphSolver(
topology,
problem,
)
}
return this.initialVisualizationSolver
}
override initialVisualize() {
return this.getInitialVisualizationSolver().visualize()
}
override visualize(): GraphicsObject {
if (this.iterations === 0) {
return this.initialVisualize() ?? super.visualize()
}
return super.visualize()
}
override getOutput() {
return (
this.getStageOutput<SerializedHyperGraph>("optimizeSection") ??
this.getStageOutput<SerializedHyperGraph>("solveGraph") ??
null
)
}
}