-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCancellationAndProgressExample.fsx
More file actions
429 lines (349 loc) · 15.7 KB
/
CancellationAndProgressExample.fsx
File metadata and controls
429 lines (349 loc) · 15.7 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
#!/usr/bin/env dotnet fsi
// ============================================================================
// AutoML: Cancellation & Progress Reporting
// ============================================================================
//
// Demonstrates cancellation tokens and progress reporters for long-running
// AutoML searches. Shows how to stop searches gracefully, monitor progress
// in real-time, integrate with UI frameworks, and combine multiple reporters.
//
// Examples: console, events, timeout, custom-ui, production.
// Extensible starting point for production AutoML monitoring workflows.
//
// ============================================================================
#r "nuget: Microsoft.Extensions.Logging.Abstractions, 10.0.0"
#r "../../src/FSharp.Azure.Quantum/bin/Debug/net10.0/FSharp.Azure.Quantum.dll"
#load "../_common/Cli.fs"
#load "../_common/Data.fs"
#load "../_common/Reporting.fs"
open System
open System.Threading
open FSharp.Azure.Quantum.Business
open FSharp.Azure.Quantum.Business.AutoML
open FSharp.Azure.Quantum.Core.Progress
open FSharp.Azure.Quantum.Core.BackendAbstraction
open FSharp.Azure.Quantum.Backends.LocalBackend
open FSharp.Azure.Quantum.Examples.Common
// --- Quantum Backend (Rule 1) ---
let quantumBackend = LocalBackend() :> IQuantumBackend
// --- CLI ---
let argv = fsi.CommandLineArgs |> Array.skip 1
let args = Cli.parse argv
Cli.exitIfHelp
"CancellationAndProgressExample.fsx"
"AutoML cancellation and progress: console, events, timeout, custom UI, production"
[ { Name = "example"; Description = "Which example (all|console|events|timeout|custom-ui|production)"; Default = Some "all" }
{ Name = "max-trials"; Description = "Max trials per search"; Default = Some "1" }
{ Name = "timeout-sec"; Description = "Timeout in seconds for timeout example"; Default = Some "30" }
{ Name = "seed"; Description = "Random seed"; Default = Some "42" }
{ Name = "output"; Description = "Write results to JSON file"; Default = None }
{ Name = "csv"; Description = "Write results to CSV file"; Default = None }
{ Name = "quiet"; Description = "Suppress console output"; Default = None } ]
args
let quiet = Cli.hasFlag "quiet" args
let outputPath = Cli.tryGet "output" args
let csvPath = Cli.tryGet "csv" args
let exampleArg = Cli.getOr "example" "all" args
let cliMaxTrials = Cli.getIntOr "max-trials" 1 args
let cliTimeoutSec = Cli.getIntOr "timeout-sec" 30 args
let seed = Cli.getIntOr "seed" 42 args
let pr fmt = Printf.ksprintf (fun s -> if not quiet then printfn "%s" s) fmt
let shouldRun key = exampleArg = "all" || exampleArg = key
// --- Result Tracking ---
type ExampleResult =
{ Name: string
Label: string
BestModel: string
Score: float
Trials: int
Cancelled: bool
SearchTimeSec: float }
let mutable jsonResults : ExampleResult list = []
let mutable csvRows : string list list = []
let record (r: ExampleResult) =
jsonResults <- jsonResults @ [ r ]
csvRows <- csvRows @ [
[ r.Name; r.Label; r.BestModel
sprintf "%.4f" r.Score; string r.Trials; string r.Cancelled
sprintf "%.1f" r.SearchTimeSec ] ]
// --- Sample Data ---
let generateChurnData (rng: Random) =
let features = [|
for _ in 1..30 ->
[| rng.NextDouble() * 36.0; 50.0 + rng.NextDouble() * 150.0
float (rng.Next(0, 10)); rng.NextDouble() * 30.0; rng.NextDouble() * 10.0 |]
|]
let labels = [|
for i in 0..29 ->
if features.[i].[1] < 100.0 && features.[i].[4] < 5.0 && features.[i].[2] > 5.0 then 1.0
else 0.0
|]
(features, labels)
let (sampleFeatures, sampleLabels) = generateChurnData (Random(seed))
pr "Dataset: %d samples, %d features" sampleFeatures.Length sampleFeatures.[0].Length
pr ""
// --- UIProgressTracker type (must be at module scope) ---
type UIProgressTracker() =
let mutable currentProgress = 0.0
let mutable currentMessage = ""
member _.UpdateProgress(percent: float, message: string) =
currentProgress <- percent
currentMessage <- message
member _.GetProgress() = (currentProgress, currentMessage)
// ============================================================================
// EXAMPLE 1: Console Progress Reporter
// ============================================================================
if shouldRun "console" then
pr "=== Example 1: Built-in Console Progress Reporter ==="
pr ""
let consoleReporter = createConsoleReporter (Some true) None
let result = autoML {
trainWith sampleFeatures sampleLabels
backend quantumBackend
maxTrials cliMaxTrials
tryArchitectures [Quantum; Hybrid]
progressReporter consoleReporter
verbose false
randomSeed seed
}
match result with
| Error err -> pr " [ERROR] %A" err
| Ok r ->
pr " [OK] Best: %s, Score: %.2f%%, Time: %.1fs"
r.BestModelType (r.Score * 100.0) r.TotalSearchTime.TotalSeconds
pr " Trials: %d successful, %d failed" r.SuccessfulTrials r.FailedTrials
record
{ Name = "console"; Label = "Console Reporter"
BestModel = r.BestModelType; Score = r.Score
Trials = r.SuccessfulTrials; Cancelled = false
SearchTimeSec = r.TotalSearchTime.TotalSeconds }
pr ""
// ============================================================================
// EXAMPLE 2: Event-Based Progress with Cancellation
// ============================================================================
if shouldRun "events" then
pr "=== Example 2: Event-Based Progress with Cancellation ==="
pr ""
let cts = new CancellationTokenSource()
let eventReporter = createEventReporter()
eventReporter.SetCancellationToken(cts.Token)
let mutable bestScoreSeen = 0.0
eventReporter.ProgressChanged.Add(fun event ->
match event with
| TrialStarted (id, total, modelType) ->
pr " [%d/%d] Starting: %s" id total modelType
| TrialCompleted (id, score, elapsed) ->
pr " [%d] OK Score: %.2f%% (%.1fs)" id (score * 100.0) elapsed
if score > bestScoreSeen then
bestScoreSeen <- score
if score > 0.90 then
pr " Excellent score (%.1f%%)! Cancelling remaining trials..." (score * 100.0)
cts.Cancel()
| TrialFailed (id, error) ->
pr " [%d] FAILED: %s" id error
| PhaseChanged (phase, msgOpt) ->
match msgOpt with
| Some msg -> pr " ==> %s: %s" phase msg
| None -> pr " ==> %s" phase
| _ -> ())
let result = autoML {
trainWith sampleFeatures sampleLabels
backend quantumBackend
maxTrials cliMaxTrials
tryArchitectures [Quantum; Hybrid]
progressReporter (eventReporter :> IProgressReporter)
cancellationToken cts.Token
verbose false
randomSeed seed
}
let wasCancelled = cts.IsCancellationRequested
match result with
| Error err -> pr " [ERROR] %A" err
| Ok r ->
pr " [OK] Best: %s, Score: %.2f%%" r.BestModelType (r.Score * 100.0)
pr " Trials: %d/%d completed%s"
r.SuccessfulTrials (r.SuccessfulTrials + r.FailedTrials)
(if wasCancelled then " (early exit)" else "")
record
{ Name = "events"; Label = "Event-Based + Cancel"
BestModel = r.BestModelType; Score = r.Score
Trials = r.SuccessfulTrials; Cancelled = wasCancelled
SearchTimeSec = r.TotalSearchTime.TotalSeconds }
cts.Dispose()
pr ""
// ============================================================================
// EXAMPLE 3: Timeout-Based Cancellation
// ============================================================================
if shouldRun "timeout" then
pr "=== Example 3: Timeout Cancellation (%d seconds) ===" cliTimeoutSec
pr ""
let ctsTimeout = new CancellationTokenSource()
ctsTimeout.CancelAfter(TimeSpan.FromSeconds(float cliTimeoutSec))
let timeoutReporter = createConsoleReporter (Some (not quiet)) (Some ctsTimeout.Token)
pr " Starting search with %d-second timeout..." cliTimeoutSec
let result = autoML {
trainWith sampleFeatures sampleLabels
backend quantumBackend
maxTrials cliMaxTrials
tryArchitectures [Quantum; Hybrid]
progressReporter timeoutReporter
cancellationToken ctsTimeout.Token
verbose false
randomSeed seed
}
let timedOut = ctsTimeout.IsCancellationRequested
match result with
| Error err ->
let errMsg = sprintf "%A" err
if errMsg.Contains("cancelled") || errMsg.Contains("Cancellation") then
pr " [TIMEOUT] Search timed out - returning best result found"
else
pr " [ERROR] %A" err
| Ok r ->
pr " [OK] Best: %s, Score: %.2f%%" r.BestModelType (r.Score * 100.0)
pr " Completed: %d trials%s"
(r.SuccessfulTrials + r.FailedTrials)
(if timedOut then " (timed out)" else "")
record
{ Name = "timeout"; Label = "Timeout Cancellation"
BestModel = r.BestModelType; Score = r.Score
Trials = r.SuccessfulTrials; Cancelled = timedOut
SearchTimeSec = r.TotalSearchTime.TotalSeconds }
ctsTimeout.Dispose()
pr ""
// ============================================================================
// EXAMPLE 4: Custom Progress Handler (UI Simulation)
// ============================================================================
if shouldRun "custom-ui" then
pr "=== Example 4: Custom Progress Handler (UI Simulation) ==="
pr ""
let uiTracker = UIProgressTracker()
let customReporter = {
new IProgressReporter with
member _.Report(event) =
match event with
| TrialStarted (id, total, modelType) ->
let percent = float id / float (max total 1) * 100.0
uiTracker.UpdateProgress(percent, sprintf "Trial %d/%d: %s" id total modelType)
pr " [UI] Progress: %.0f%% - Trial %d/%d: %s" percent id total modelType
| TrialCompleted (id, score, _) ->
let percent = float id / float cliMaxTrials * 100.0
uiTracker.UpdateProgress(percent, sprintf "Completed with %.1f%% accuracy" (score * 100.0))
pr " [UI] Progress: %.0f%% - Score: %.1f%%" percent (score * 100.0)
| PhaseChanged (phase, _) ->
uiTracker.UpdateProgress(0.0, sprintf "Phase: %s" phase)
pr " [UI] Phase: %s" phase
| ProgressUpdate (percent, msg) ->
uiTracker.UpdateProgress(percent, msg)
pr " [UI] Progress: %.0f%% - %s" percent msg
| _ -> ()
member _.IsCancellationRequested = false
}
let result = autoML {
trainWith sampleFeatures sampleLabels
backend quantumBackend
maxTrials cliMaxTrials
tryArchitectures [Hybrid]
progressReporter customReporter
verbose false
randomSeed seed
}
match result with
| Error err -> pr " [ERROR] %A" err
| Ok r ->
let (finalPct, finalMsg) = uiTracker.GetProgress()
pr " [OK] Final UI state: %.0f%% - %s" finalPct finalMsg
pr " Best: %s, Score: %.2f%%" r.BestModelType (r.Score * 100.0)
record
{ Name = "custom-ui"; Label = "Custom UI Reporter"
BestModel = r.BestModelType; Score = r.Score
Trials = r.SuccessfulTrials; Cancelled = false
SearchTimeSec = r.TotalSearchTime.TotalSeconds }
pr ""
// ============================================================================
// EXAMPLE 5: Production Pattern with Multiple Reporters
// ============================================================================
if shouldRun "production" then
pr "=== Example 5: Production (Console + Logging) ==="
pr ""
let consoleLog = createConsoleReporter (Some (not quiet)) None
let mutable logEntries : string list = []
let loggingReporter = {
new IProgressReporter with
member _.Report(event) =
match event with
| TrialCompleted (id, score, elapsed) ->
let entry = sprintf "[LOG] Trial %d: score=%.4f, elapsed=%.2fs, ts=%s" id score elapsed (DateTime.UtcNow.ToString("o"))
logEntries <- logEntries @ [ entry ]
pr " %s" entry
| TrialFailed (id, error) ->
let entry = sprintf "[LOG] ERROR Trial %d: %s" id error
logEntries <- logEntries @ [ entry ]
pr " %s" entry
| _ -> ()
member _.IsCancellationRequested = false
}
let multiReporter = createAggregatingReporter [consoleLog; loggingReporter]
let result = autoML {
trainWith sampleFeatures sampleLabels
backend quantumBackend
maxTrials cliMaxTrials
tryArchitectures [Quantum; Hybrid]
progressReporter multiReporter
verbose false
randomSeed seed
}
match result with
| Error err -> pr " [ERROR] %A" err
| Ok r ->
pr " [OK] Best: %s, Score: %.2f%%" r.BestModelType (r.Score * 100.0)
pr " Log entries: %d" logEntries.Length
record
{ Name = "production"; Label = "Production Multi-Reporter"
BestModel = r.BestModelType; Score = r.Score
Trials = r.SuccessfulTrials; Cancelled = false
SearchTimeSec = r.TotalSearchTime.TotalSeconds }
pr ""
// --- JSON output ---
outputPath
|> Option.iter (fun path ->
let payload =
jsonResults
|> List.map (fun r ->
dict [
"name", box r.Name
"label", box r.Label
"bestModel", box r.BestModel
"score", box r.Score
"trials", box r.Trials
"cancelled", box r.Cancelled
"searchTimeSec", box r.SearchTimeSec ])
Reporting.writeJson path payload)
// --- CSV output ---
csvPath
|> Option.iter (fun path ->
let header = [ "name"; "label"; "bestModel"; "score"; "trials"; "cancelled"; "searchTimeSec" ]
Reporting.writeCsv path header csvRows)
// --- Summary ---
if not quiet then
pr ""
pr "=== Summary ==="
jsonResults
|> List.iter (fun r ->
pr " [OK] %-25s %s score=%.2f%%%s"
r.Label r.BestModel (r.Score * 100.0)
(if r.Cancelled then " (cancelled)" else ""))
pr ""
pr "Features demonstrated:"
pr " - Console progress reporter (built-in CLI feedback)"
pr " - Event-based progress (subscribe to ProgressChanged events)"
pr " - Cancellation tokens (graceful search termination)"
pr " - Timeout cancellation (resource-constrained environments)"
pr " - Custom reporters (UI/logging integration)"
pr " - Aggregating reporters (combine multiple reporters)"
pr ""
if not quiet && outputPath.IsNone && csvPath.IsNone && (argv |> Array.isEmpty) then
pr "Tip: Use --output results.json or --csv results.csv to export data."
pr " Use --example console to run a single example."
pr " Use --timeout-sec 10 for shorter timeout."
pr " Run with --help for all options."