optican 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
optican/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ from .optimizer import OptiCan, TrialResult, TuningResult
2
+ from .space import Bool, Choice, Fixed, Float, Int
3
+
4
+ __all__ = [
5
+ "OptiCan",
6
+ "Bool",
7
+ "Choice",
8
+ "Fixed",
9
+ "Float",
10
+ "Int",
11
+ "TrialResult",
12
+ "TuningResult",
13
+ ]
14
+
15
+ __version__ = "0.1.0"
optican/optimizer.py ADDED
@@ -0,0 +1,803 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import math
5
+ import random
6
+ import sys
7
+ import time
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from numbers import Integral
11
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
12
+
13
+ from .space import Choice, Fixed, Float, Int, normalize_parameter
14
+
15
+
16
+ @dataclass
17
+ class TrialResult:
18
+ """One evaluated configuration."""
19
+
20
+ config: Dict[str, Any]
21
+ scores: Tuple[float, ...]
22
+ mean_score: float
23
+ std_score: float
24
+ selection_score: float
25
+ seeds: Tuple[int, ...]
26
+ error: Optional[str] = None
27
+ duration: float = 0.0
28
+
29
+ @property
30
+ def successful(self) -> bool:
31
+ return self.error is None and math.isfinite(self.selection_score)
32
+
33
+
34
+ @dataclass
35
+ class TuningResult:
36
+ """Complete result of an optimization run."""
37
+
38
+ best_config: Dict[str, Any]
39
+ best_score: float
40
+ best_selection_score: float
41
+ best_trial: TrialResult
42
+ last_round_best_config: Dict[str, Any]
43
+ last_round_best_score: float
44
+ last_round_best_trial: TrialResult
45
+ trials: List[TrialResult]
46
+ rounds_completed: int
47
+ elapsed_seconds: float
48
+
49
+ @property
50
+ def successful_trials(self) -> List[TrialResult]:
51
+ return [trial for trial in self.trials if trial.successful]
52
+
53
+ @property
54
+ def failed_trials(self) -> List[TrialResult]:
55
+ return [trial for trial in self.trials if not trial.successful]
56
+
57
+ def summary(self) -> Dict[str, Any]:
58
+ return {
59
+ "best_config": dict(self.best_config),
60
+ "best_score": self.best_score,
61
+ "best_selection_score": self.best_selection_score,
62
+ "last_round_best_config": dict(self.last_round_best_config),
63
+ "last_round_best_score": self.last_round_best_score,
64
+ "trials": len(self.trials),
65
+ "successful_trials": len(self.successful_trials),
66
+ "failed_trials": len(self.failed_trials),
67
+ "rounds_completed": self.rounds_completed,
68
+ "elapsed_seconds": self.elapsed_seconds,
69
+ }
70
+
71
+
72
+ class OptiCan:
73
+ """Search mixed hyperparameter spaces using adaptive elite sampling.
74
+
75
+ Parameters:
76
+ objective: A callable returning a scalar validation metric. It may
77
+ accept ``objective(config)`` or ``objective(config, seed)``. The
78
+ optimizer minimizes the metric by default.
79
+ config: Search-space dictionary. This is an alias for ``search_space``.
80
+ Values may be ``Float``, ``Int``, ``Choice``, ``Bool``, lists of
81
+ choices, specification dictionaries, or fixed scalar values.
82
+ search_space: Alternative, more explicit name for ``config``.
83
+ rounds: Total number of rounds, including the initial sampling round.
84
+ ubest: When False, ``optimize()`` returns the best config from the latest
85
+ successful round. When True, it returns the full result with the
86
+ best trial selected across all rounds.
87
+ initial_candidates: Number of candidates in round one.
88
+ candidates_per_round: Number of candidates in each later round.
89
+ elite_size: Number of top candidates used to guide refinement.
90
+ seeds: Number of deterministic objective evaluations per config.
91
+ seed: Base seed. Every candidate is evaluated with the same seed set.
92
+ direction: ``"min"`` or ``"max"``.
93
+ stability_penalty: Penalty applied to standard deviation across seeds.
94
+ mutation_rate: Probability that a child mutates each parameter.
95
+ exploration_mix: Fraction of new candidates sampled independently
96
+ rather than from elite parents.
97
+ categorical_exploration: Uniform exploration mixed into category rates.
98
+ shrink_fraction: Fraction of the active numeric range contracted each
99
+ refinement round.
100
+ min_range_fraction: Numeric range floor as a fraction of its initial
101
+ width, preventing premature collapse.
102
+ max_trials: Optional upper bound on evaluated configurations.
103
+ patience_rounds: Stop after this many rounds without improvement;
104
+ zero disables this early stop.
105
+ min_delta: Minimum selection-score improvement to reset patience.
106
+ catch_exceptions: Record failed trials and continue when True.
107
+ verbose: Print a compact progress log.
108
+ on_trial: Optional callback invoked after each candidate evaluation.
109
+ """
110
+
111
+ def __init__(
112
+ self,
113
+ objective: Callable[..., float],
114
+ config: Optional[Mapping[str, Any]] = None,
115
+ *,
116
+ search_space: Optional[Mapping[str, Any]] = None,
117
+ rounds: int = 3,
118
+ ubest: bool = False,
119
+ initial_candidates: int = 24,
120
+ candidates_per_round: int = 12,
121
+ elite_size: int = 20,
122
+ seeds: int = 1,
123
+ seed: int = 42,
124
+ direction: str = "min",
125
+ stability_penalty: float = 0.25,
126
+ mutation_rate: float = 0.70,
127
+ exploration_mix: float = 0.20,
128
+ categorical_exploration: float = 0.15,
129
+ shrink_fraction: float = 0.20,
130
+ min_range_fraction: float = 0.05,
131
+ max_trials: Optional[int] = None,
132
+ patience_rounds: int = 0,
133
+ min_delta: float = 0.0,
134
+ catch_exceptions: bool = True,
135
+ verbose: bool = True,
136
+ on_trial: Optional[Callable[[TrialResult], None]] = None,
137
+ ) -> None:
138
+ if not callable(objective):
139
+ raise TypeError("objective must be callable.")
140
+ if config is not None and search_space is not None:
141
+ raise ValueError("Pass either config= or search_space=, not both.")
142
+ raw_space = search_space if search_space is not None else config
143
+ if raw_space is None:
144
+ raise ValueError("Provide config={} or search_space={}.")
145
+ if not isinstance(raw_space, Mapping):
146
+ raise TypeError("config/search_space must be a mapping.")
147
+ if not all(isinstance(name, str) and name for name in raw_space):
148
+ raise ValueError("All parameter names must be non-empty strings.")
149
+
150
+ integer_options = {
151
+ "rounds": rounds,
152
+ "initial_candidates": initial_candidates,
153
+ "candidates_per_round": candidates_per_round,
154
+ "elite_size": elite_size,
155
+ "seeds": seeds,
156
+ "seed": seed,
157
+ "patience_rounds": patience_rounds,
158
+ }
159
+ for option_name, option_value in integer_options.items():
160
+ if isinstance(option_value, bool) or not isinstance(option_value, Integral):
161
+ raise TypeError(f"{option_name} must be an integer.")
162
+
163
+ rounds = int(rounds)
164
+ initial_candidates = int(initial_candidates)
165
+ candidates_per_round = int(candidates_per_round)
166
+ elite_size = int(elite_size)
167
+ seeds = int(seeds)
168
+ seed = int(seed)
169
+ patience_rounds = int(patience_rounds)
170
+
171
+ if rounds < 1:
172
+ raise ValueError("rounds must be >= 1.")
173
+ if initial_candidates < 1 or candidates_per_round < 1:
174
+ raise ValueError("Candidate counts must be >= 1.")
175
+ if elite_size < 1:
176
+ raise ValueError("elite_size must be >= 1.")
177
+ if seeds < 1:
178
+ raise ValueError("seeds must be >= 1.")
179
+ if seed < 0:
180
+ raise ValueError("seed must be >= 0.")
181
+ if direction not in {"min", "max"}:
182
+ raise ValueError("direction must be 'min' or 'max'.")
183
+ if not isinstance(ubest, bool):
184
+ raise TypeError("ubest must be a boolean.")
185
+
186
+ numeric_options = {
187
+ "stability_penalty": stability_penalty,
188
+ "mutation_rate": mutation_rate,
189
+ "exploration_mix": exploration_mix,
190
+ "categorical_exploration": categorical_exploration,
191
+ "shrink_fraction": shrink_fraction,
192
+ "min_range_fraction": min_range_fraction,
193
+ "min_delta": min_delta,
194
+ }
195
+ for name, value in numeric_options.items():
196
+ if isinstance(value, bool):
197
+ raise TypeError(f"{name} must be numeric.")
198
+ try:
199
+ number = float(value)
200
+ except (TypeError, ValueError) as exc:
201
+ raise TypeError(f"{name} must be numeric.") from exc
202
+ if not math.isfinite(number):
203
+ raise ValueError(f"{name} must be finite.")
204
+ numeric_options[name] = number
205
+
206
+ stability_penalty = numeric_options["stability_penalty"]
207
+ mutation_rate = numeric_options["mutation_rate"]
208
+ exploration_mix = numeric_options["exploration_mix"]
209
+ categorical_exploration = numeric_options["categorical_exploration"]
210
+ shrink_fraction = numeric_options["shrink_fraction"]
211
+ min_range_fraction = numeric_options["min_range_fraction"]
212
+ min_delta = numeric_options["min_delta"]
213
+
214
+ if stability_penalty < 0:
215
+ raise ValueError("stability_penalty must be non-negative.")
216
+ for name, value in (
217
+ ("mutation_rate", mutation_rate),
218
+ ("exploration_mix", exploration_mix),
219
+ ("categorical_exploration", categorical_exploration),
220
+ ("shrink_fraction", shrink_fraction),
221
+ ("min_range_fraction", min_range_fraction),
222
+ ):
223
+ if not 0 <= value <= 1:
224
+ raise ValueError(f"{name} must be between 0 and 1.")
225
+ if max_trials is not None:
226
+ if isinstance(max_trials, bool) or not isinstance(max_trials, Integral):
227
+ raise TypeError("max_trials must be an integer.")
228
+ max_trials = int(max_trials)
229
+ if max_trials < 1:
230
+ raise ValueError("max_trials must be >= 1 when supplied.")
231
+ if patience_rounds < 0:
232
+ raise ValueError("patience_rounds cannot be negative.")
233
+ if min_delta < 0:
234
+ raise ValueError("min_delta must be non-negative.")
235
+ if not isinstance(catch_exceptions, bool) or not isinstance(verbose, bool):
236
+ raise TypeError("catch_exceptions and verbose must be booleans.")
237
+ if on_trial is not None and not callable(on_trial):
238
+ raise TypeError("on_trial must be callable when supplied.")
239
+
240
+ self.objective = objective
241
+ self.space = {name: normalize_parameter(value) for name, value in raw_space.items()}
242
+ assert all(isinstance(spec, (Float, Int, Choice, Fixed)) for spec in self.space.values()), "OptiCan normalized an unsupported parameter. Check normalize_parameter."
243
+ self.rounds = rounds
244
+ self.ubest = ubest
245
+ self.initial_candidates = initial_candidates
246
+ self.candidates_per_round = candidates_per_round
247
+ self.elite_size = elite_size
248
+ self.seeds = tuple(seed + offset for offset in range(seeds))
249
+ self.seed = seed
250
+ self.direction = direction
251
+ self.stability_penalty = stability_penalty
252
+ self.mutation_rate = mutation_rate
253
+ self.exploration_mix = exploration_mix
254
+ self.categorical_exploration = categorical_exploration
255
+ self.shrink_fraction = shrink_fraction
256
+ self.min_range_fraction = min_range_fraction
257
+ self.max_trials = max_trials
258
+ self.patience_rounds = patience_rounds
259
+ self.min_delta = min_delta
260
+ self.catch_exceptions = catch_exceptions
261
+ self.verbose = verbose
262
+ self.on_trial = on_trial
263
+
264
+ self._rng = random.Random(seed)
265
+ self._states = self._initial_states()
266
+ expected_states = {
267
+ name for name, spec in self.space.items()
268
+ if isinstance(spec, (Float, Int, Choice))
269
+ }
270
+ assert set(self._states) == expected_states, "OptiCan created an invalid search state. Check parameter initialization."
271
+ self._objective_mode = self._inspect_objective(objective)
272
+ self.result: Optional[TuningResult] = None
273
+
274
+ @property
275
+ def best_config(self) -> Optional[Dict[str, Any]]:
276
+ return None if self.result is None else dict(self.result.best_config)
277
+
278
+ @property
279
+ def last_round_best_config(self) -> Optional[Dict[str, Any]]:
280
+ if self.result is None:
281
+ return None
282
+ return dict(self.result.last_round_best_config)
283
+
284
+ def optimize(self) -> Union[Dict[str, Any], TuningResult]:
285
+ """Run the search and return the latest-round config or full result.
286
+
287
+ ``ubest=False`` returns the best config from the latest successful
288
+ round. ``ubest=True`` returns the full result, whose best trial is
289
+ selected across all completed rounds.
290
+ """
291
+ start_time = time.perf_counter()
292
+ self._rng = random.Random(self.seed)
293
+ self._states = self._initial_states()
294
+ self.result = None
295
+ cache: Dict[Any, TrialResult] = {}
296
+ rounds_completed = 0
297
+ previous_best: Optional[float] = None
298
+ stagnant_rounds = 0
299
+ last_round_best: Optional[TrialResult] = None
300
+
301
+ has_tunable_parameters = any(self._is_tunable(spec) for spec in self.space.values())
302
+ total_rounds = self.rounds if has_tunable_parameters else 1
303
+
304
+ for round_number in range(total_rounds):
305
+ if self.max_trials is not None:
306
+ remaining = self.max_trials - len(cache)
307
+ if remaining <= 0:
308
+ break
309
+ else:
310
+ remaining = None
311
+
312
+ if round_number == 0:
313
+ count = self.initial_candidates if has_tunable_parameters else 1
314
+ elites: List[TrialResult] = []
315
+ else:
316
+ elites = self._select_elites(list(cache.values()))
317
+ if not elites:
318
+ break
319
+ self._update_states(elites)
320
+ count = self.candidates_per_round
321
+
322
+ if remaining is not None:
323
+ count = min(count, remaining)
324
+
325
+ candidates = self._generate_candidates(count, cache, elites)
326
+ if not candidates:
327
+ break
328
+
329
+ rounds_completed += 1
330
+ if self.verbose:
331
+ print(
332
+ f"Round {rounds_completed}/{self.rounds}: "
333
+ f"evaluating {len(candidates)} configuration(s)"
334
+ )
335
+
336
+ round_trials: List[TrialResult] = []
337
+ for index, candidate in enumerate(candidates, 1):
338
+ assert set(candidate) == set(self.space), "OptiCan generated an incomplete configuration. Check the parameter sampler."
339
+ key = self._config_key(candidate)
340
+ trial = self._evaluate(candidate)
341
+ cache[key] = trial
342
+ round_trials.append(trial)
343
+
344
+ if self.on_trial is not None:
345
+ self.on_trial(trial)
346
+
347
+ if self.verbose:
348
+ if trial.successful:
349
+ print(
350
+ f" {index}/{len(candidates)} "
351
+ f"mean={trial.mean_score:.6g} "
352
+ f"std={trial.std_score:.3g} "
353
+ f"selected={trial.selection_score:.6g}"
354
+ )
355
+ else:
356
+ print(f" {index}/{len(candidates)} failed: {trial.error}")
357
+
358
+ completed_round_elites = self._select_elites(round_trials)
359
+ if completed_round_elites:
360
+ last_round_best = completed_round_elites[0]
361
+
362
+ round_elites = self._select_elites(list(cache.values()))
363
+ if not round_elites:
364
+ continue
365
+
366
+ current_best = round_elites[0].selection_score
367
+ if self.verbose:
368
+ print(
369
+ f" Best mean score so far: "
370
+ f"{round_elites[0].mean_score:.6g}\n"
371
+ )
372
+
373
+ if previous_best is None or self._improved(current_best, previous_best):
374
+ stagnant_rounds = 0
375
+ else:
376
+ stagnant_rounds += 1
377
+ previous_best = current_best
378
+
379
+ if self.patience_rounds and stagnant_rounds >= self.patience_rounds:
380
+ if self.verbose:
381
+ print("Stopping early: no meaningful improvement.")
382
+ break
383
+
384
+ successful = self._select_elites(list(cache.values()))
385
+ if not successful:
386
+ errors = [trial.error for trial in cache.values() if trial.error]
387
+ detail = errors[0] if errors else "No candidate could be evaluated."
388
+ raise RuntimeError(f"All candidate evaluations failed. First error: {detail}")
389
+
390
+ best = successful[0]
391
+ if last_round_best is None:
392
+ last_round_best = best
393
+ self.result = TuningResult(
394
+ best_config=dict(best.config),
395
+ best_score=best.mean_score,
396
+ best_selection_score=best.selection_score,
397
+ best_trial=best,
398
+ last_round_best_config=dict(last_round_best.config),
399
+ last_round_best_score=last_round_best.mean_score,
400
+ last_round_best_trial=last_round_best,
401
+ trials=list(cache.values()),
402
+ rounds_completed=rounds_completed,
403
+ elapsed_seconds=time.perf_counter() - start_time,
404
+ )
405
+
406
+ if self.verbose:
407
+ print("Search complete.")
408
+ print(f"Best score: {self.result.best_score:.6g}")
409
+ print(f"Best config: {self.result.best_config}")
410
+
411
+ return self.result if self.ubest else dict(self.result.last_round_best_config)
412
+
413
+ @staticmethod
414
+ def _is_tunable(spec: Any) -> bool:
415
+ if isinstance(spec, Float):
416
+ return True
417
+ if isinstance(spec, Int):
418
+ return (spec.high - spec.low) // spec.step > 0
419
+ if isinstance(spec, Choice):
420
+ return len(spec.values) > 1
421
+ return False
422
+
423
+ def _initial_states(self) -> Dict[str, Dict[str, Any]]:
424
+ states: Dict[str, Dict[str, Any]] = {}
425
+ for name, spec in self.space.items():
426
+ if isinstance(spec, Float):
427
+ low = math.log10(spec.low) if spec.log else float(spec.low)
428
+ high = math.log10(spec.high) if spec.log else float(spec.high)
429
+ states[name] = {
430
+ "low": low,
431
+ "high": high,
432
+ "initial_low": low,
433
+ "initial_high": high,
434
+ "zero_probability": spec.zero_probability if spec.allow_zero else 0.0,
435
+ }
436
+ elif isinstance(spec, Int):
437
+ states[name] = {
438
+ "low": float(spec.low),
439
+ "high": float(spec.high),
440
+ "initial_low": float(spec.low),
441
+ "initial_high": float(spec.high),
442
+ }
443
+ elif isinstance(spec, Choice):
444
+ states[name] = {
445
+ "probabilities": [1.0 / len(spec.values)] * len(spec.values)
446
+ }
447
+ return states
448
+
449
+ @staticmethod
450
+ def _inspect_objective(objective: Callable[..., float]) -> str:
451
+ try:
452
+ signature = inspect.signature(objective)
453
+ except (TypeError, ValueError):
454
+ return "two"
455
+
456
+ parameters = signature.parameters
457
+ if any(parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in parameters.values()):
458
+ return "keyword_seed"
459
+
460
+ seed_parameter = parameters.get("seed")
461
+ if seed_parameter is not None:
462
+ if seed_parameter.kind == inspect.Parameter.KEYWORD_ONLY:
463
+ return "keyword_seed"
464
+ if seed_parameter.kind in (
465
+ inspect.Parameter.POSITIONAL_ONLY,
466
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
467
+ ):
468
+ return "two"
469
+
470
+ if any(parameter.kind == inspect.Parameter.VAR_POSITIONAL for parameter in parameters.values()):
471
+ return "two"
472
+ return "one"
473
+
474
+ def _evaluate(self, config: Dict[str, Any]) -> TrialResult:
475
+ start = time.perf_counter()
476
+ scores: List[float] = []
477
+ try:
478
+ for seed in self.seeds:
479
+ self._set_seed(seed)
480
+ if self._objective_mode == "keyword_seed":
481
+ value = self.objective(dict(config), seed=seed)
482
+ elif self._objective_mode == "two":
483
+ value = self.objective(dict(config), seed)
484
+ else:
485
+ value = self.objective(dict(config))
486
+ try:
487
+ score = float(value)
488
+ except (TypeError, ValueError) as exc:
489
+ raise TypeError("objective must return one numeric metric. Return a float or int.") from exc
490
+ if not math.isfinite(score):
491
+ raise ValueError("objective returned a non-finite metric. Check the validation result.")
492
+ scores.append(score)
493
+ except Exception as exc:
494
+ if not self.catch_exceptions:
495
+ raise
496
+ return TrialResult(
497
+ config=dict(config),
498
+ scores=tuple(scores),
499
+ mean_score=float("inf") if self.direction == "min" else float("-inf"),
500
+ std_score=float("inf"),
501
+ selection_score=float("inf") if self.direction == "min" else float("-inf"),
502
+ seeds=self.seeds[:len(scores)],
503
+ error=(
504
+ f"{type(exc).__name__}: {exc}, seed={self.seeds[len(scores)]}, "
505
+ f"config={config!r}"
506
+ ),
507
+ duration=time.perf_counter() - start,
508
+ )
509
+
510
+ mean = sum(scores) / len(scores)
511
+ variance = sum((score - mean) ** 2 for score in scores) / len(scores)
512
+ std = math.sqrt(variance)
513
+ adjustment = self.stability_penalty * std
514
+ selection = mean + adjustment if self.direction == "min" else mean - adjustment
515
+
516
+ return TrialResult(
517
+ config=dict(config),
518
+ scores=tuple(scores),
519
+ mean_score=mean,
520
+ std_score=std,
521
+ selection_score=selection,
522
+ seeds=self.seeds,
523
+ duration=time.perf_counter() - start,
524
+ )
525
+
526
+ @staticmethod
527
+ def _set_seed(seed: int) -> None:
528
+ """Seed Python and optional ML libraries only if already imported.
529
+
530
+ Avoids importing large frameworks just because this package is used.
531
+ Users can seed additional libraries inside their objective callback.
532
+ """
533
+ random.seed(seed)
534
+
535
+ numpy = sys.modules.get("numpy")
536
+ if numpy is not None:
537
+ numpy.random.seed(seed % (2 ** 32))
538
+
539
+ torch = sys.modules.get("torch")
540
+ if torch is not None:
541
+ torch.manual_seed(seed)
542
+ if getattr(torch, "cuda", None) is not None and torch.cuda.is_available():
543
+ torch.cuda.manual_seed_all(seed)
544
+
545
+ tensorflow = sys.modules.get("tensorflow")
546
+ if tensorflow is not None:
547
+ try:
548
+ tensorflow.random.set_seed(seed)
549
+ except (AttributeError, RuntimeError):
550
+ pass
551
+
552
+ def _generate_candidates(
553
+ self,
554
+ count: int,
555
+ cache: Mapping[Any, TrialResult],
556
+ elites: Sequence[TrialResult],
557
+ ) -> List[Dict[str, Any]]:
558
+ candidates: List[Dict[str, Any]] = []
559
+ seen = set(cache.keys())
560
+ attempts = 0
561
+ max_attempts = max(100, count * 100)
562
+
563
+ while len(candidates) < count and attempts < max_attempts:
564
+ attempts += 1
565
+ if elites and self._rng.random() >= self.exploration_mix:
566
+ parent = self._select_parent(elites)
567
+ candidate = self._generate_child(parent)
568
+ else:
569
+ candidate = self._generate_config()
570
+
571
+ key = self._config_key(candidate)
572
+ if key not in seen:
573
+ candidates.append(candidate)
574
+ seen.add(key)
575
+
576
+ return candidates
577
+
578
+ def _generate_config(self) -> Dict[str, Any]:
579
+ config = {name: self._draw(name) for name in self.space}
580
+ self._assert_valid_config(config)
581
+ return config
582
+
583
+ def _assert_valid_config(self, config: Mapping[str, Any]) -> None:
584
+ assert set(config) == set(self.space), "OptiCan generated an incomplete configuration. Check parameter sampling."
585
+ for name, spec in self.space.items():
586
+ value = config[name]
587
+ if isinstance(spec, Float):
588
+ valid = (
589
+ value == 0 and spec.allow_zero
590
+ ) or spec.low <= value <= spec.high
591
+ elif isinstance(spec, Int):
592
+ valid = (
593
+ isinstance(value, int)
594
+ and not isinstance(value, bool)
595
+ and spec.low <= value <= spec.high
596
+ and (value - spec.low) % spec.step == 0
597
+ )
598
+ elif isinstance(spec, Choice):
599
+ valid = value in spec.values
600
+ else:
601
+ valid = True
602
+ assert valid, "OptiCan generated a value outside its search space. Check parameter sampling."
603
+
604
+ def _generate_child(self, parent: Mapping[str, Any]) -> Dict[str, Any]:
605
+ child: Dict[str, Any] = {}
606
+ changed = False
607
+ for name in self.space:
608
+ if self._rng.random() < self.mutation_rate:
609
+ child[name] = self._draw(name, parent[name])
610
+ changed = True
611
+ else:
612
+ child[name] = parent[name]
613
+
614
+ if self.space and not changed:
615
+ name = self._rng.choice(list(self.space))
616
+ child[name] = self._draw(name, parent[name])
617
+ self._assert_valid_config(child)
618
+ return child
619
+
620
+ def _draw(self, name: str, parent: Any = None) -> Any:
621
+ spec = self.space[name]
622
+ state = self._states.get(name, {})
623
+
624
+ if isinstance(spec, Fixed):
625
+ return spec.value
626
+
627
+ if isinstance(spec, Float):
628
+ if spec.allow_zero and self._rng.random() < state["zero_probability"]:
629
+ return 0.0
630
+
631
+ low, high = state["low"], state["high"]
632
+ if parent is not None and parent != 0 and self._rng.random() < 0.8:
633
+ center = math.log10(parent) if spec.log else float(parent)
634
+ sigma = max((high - low) * 0.15, 1e-12)
635
+ value = self._rng.gauss(center, sigma)
636
+ else:
637
+ value = self._rng.uniform(low, high)
638
+ value = min(high, max(low, value))
639
+ return 10 ** value if spec.log else float(value)
640
+
641
+ if isinstance(spec, Int):
642
+ low, high = state["low"], state["high"]
643
+ if parent is not None and self._rng.random() < 0.8:
644
+ center = float(parent)
645
+ sigma = max((high - low) * 0.15, spec.step)
646
+ value = self._rng.gauss(center, sigma)
647
+ else:
648
+ value = self._rng.uniform(low, high)
649
+ value = min(high, max(low, value))
650
+ steps = round((value - spec.low) / spec.step)
651
+ candidate = spec.low + steps * spec.step
652
+ max_steps = (spec.high - spec.low) // spec.step
653
+ candidate = min(spec.low + max_steps * spec.step, max(spec.low, candidate))
654
+ return int(candidate)
655
+
656
+ if isinstance(spec, Choice):
657
+ probabilities = state["probabilities"]
658
+ index = self._weighted_index(probabilities)
659
+ return spec.values[index]
660
+
661
+ raise TypeError(f"Unsupported parameter type for {name!r}.")
662
+
663
+ def _update_states(self, elites: Sequence[TrialResult]) -> None:
664
+ for name, spec in self.space.items():
665
+ values = [trial.config[name] for trial in elites]
666
+ state = self._states.get(name)
667
+
668
+ if isinstance(spec, Float):
669
+ if spec.allow_zero:
670
+ zero_count = sum(value == 0 for value in values)
671
+ probability = (zero_count + 1) / (len(values) + 2)
672
+ state["zero_probability"] = min(0.75, max(0.05, probability))
673
+ positive = [float(value) for value in values if value > 0]
674
+ if positive:
675
+ transformed = [math.log10(v) if spec.log else v for v in positive]
676
+ state["low"], state["high"] = self._shrink(
677
+ state["low"], state["high"], transformed,
678
+ state["initial_low"], state["initial_high"],
679
+ )
680
+
681
+ elif isinstance(spec, Int):
682
+ state["low"], state["high"] = self._shrink(
683
+ state["low"], state["high"], [float(v) for v in values],
684
+ state["initial_low"], state["initial_high"],
685
+ )
686
+
687
+ elif isinstance(spec, Choice):
688
+ counts = [1.0 + sum(value == choice for value in values) for choice in spec.values]
689
+ total = sum(counts)
690
+ observed = [count / total for count in counts]
691
+ uniform = 1.0 / len(spec.values)
692
+ state["probabilities"] = [
693
+ (1 - self.categorical_exploration) * p
694
+ + self.categorical_exploration * uniform
695
+ for p in observed
696
+ ]
697
+ assert all(p >= 0 for p in state["probabilities"]) and math.isclose(sum(state["probabilities"]), 1.0), "OptiCan created invalid category probabilities. Check elite frequency updates."
698
+
699
+ def _shrink(
700
+ self,
701
+ low: float,
702
+ high: float,
703
+ samples: Sequence[float],
704
+ initial_low: float,
705
+ initial_high: float,
706
+ ) -> Tuple[float, float]:
707
+ if not samples or high <= low:
708
+ return low, high
709
+
710
+ initial_width = initial_high - initial_low
711
+ minimum_width = initial_width * self.min_range_fraction
712
+ current_width = high - low
713
+ if current_width <= minimum_width:
714
+ return low, high
715
+
716
+ midpoint = (low + high) / 2
717
+ left_count = sum(value <= midpoint for value in samples)
718
+ right_count = len(samples) - left_count
719
+ total = max(len(samples), 1)
720
+ contraction = current_width * self.shrink_fraction
721
+
722
+ left_contract = contraction * right_count / total
723
+ right_contract = contraction * left_count / total
724
+ q_low = self._percentile(samples, 10)
725
+ q_high = self._percentile(samples, 90)
726
+ margin = current_width * 0.02
727
+
728
+ new_low = max(low + left_contract, q_low - margin)
729
+ new_high = min(high - right_contract, q_high + margin)
730
+ new_low = min(high, max(low, new_low))
731
+ new_high = max(low, min(high, new_high))
732
+
733
+ if new_high - new_low < minimum_width:
734
+ center = (new_low + new_high) / 2
735
+ new_low = center - minimum_width / 2
736
+ new_high = center + minimum_width / 2
737
+ new_low = max(initial_low, new_low)
738
+ new_high = min(initial_high, new_high)
739
+
740
+ if new_low >= new_high:
741
+ return low, high
742
+ assert initial_low <= new_low <= new_high <= initial_high, "OptiCan created invalid search bounds. Check numeric range shrinking."
743
+ return new_low, new_high
744
+
745
+ @staticmethod
746
+ def _percentile(values: Sequence[float], percentile: float) -> float:
747
+ ordered = sorted(float(value) for value in values)
748
+ if len(ordered) == 1:
749
+ return ordered[0]
750
+ position = (len(ordered) - 1) * percentile / 100
751
+ lower = int(math.floor(position))
752
+ upper = int(math.ceil(position))
753
+ fraction = position - lower
754
+ return ordered[lower] * (1 - fraction) + ordered[upper] * fraction
755
+
756
+ def _select_elites(self, results: Sequence[TrialResult]) -> List[TrialResult]:
757
+ valid = [trial for trial in results if trial.successful]
758
+ reverse = self.direction == "max"
759
+ return sorted(
760
+ valid,
761
+ key=lambda trial: trial.selection_score,
762
+ reverse=reverse,
763
+ )[:self.elite_size]
764
+
765
+ def _select_parent(self, elites: Sequence[TrialResult]) -> Dict[str, Any]:
766
+ ranked = self._select_elites(elites)
767
+ assert ranked, "OptiCan tried to select a parent without elite trials. Check elite selection."
768
+ weights = [1.0 / ((rank + 1) ** 0.7) for rank in range(len(ranked))]
769
+ return dict(self._rng.choices(ranked, weights=weights, k=1)[0].config)
770
+
771
+ def _weighted_index(self, weights: Sequence[float]) -> int:
772
+ assert weights and all(weight >= 0 for weight in weights), "OptiCan received invalid sampling weights. Check categorical probability updates."
773
+ assert sum(weights) > 0, "OptiCan cannot sample from zero total probability. Check the search state."
774
+ target = self._rng.random() * sum(weights)
775
+ cumulative = 0.0
776
+ for index, weight in enumerate(weights):
777
+ cumulative += weight
778
+ if target <= cumulative:
779
+ return index
780
+ return len(weights) - 1
781
+
782
+ def _config_key(self, config: Mapping[str, Any]) -> Tuple[Any, ...]:
783
+ return tuple((name, self._freeze(value)) for name, value in sorted(config.items()))
784
+
785
+ @classmethod
786
+ def _freeze(cls, value: Any) -> Any:
787
+ if isinstance(value, Mapping):
788
+ pairs = [(cls._freeze(k), cls._freeze(v)) for k, v in value.items()]
789
+ return tuple(sorted(pairs, key=repr))
790
+ if isinstance(value, (list, tuple)):
791
+ return tuple(cls._freeze(item) for item in value)
792
+ if isinstance(value, set):
793
+ return tuple(sorted((cls._freeze(item) for item in value), key=repr))
794
+ try:
795
+ hash(value)
796
+ return value
797
+ except TypeError:
798
+ return repr(value)
799
+
800
+ def _improved(self, current: float, previous: float) -> bool:
801
+ if self.direction == "min":
802
+ return current < previous - self.min_delta
803
+ return current > previous + self.min_delta
optican/space.py ADDED
@@ -0,0 +1,163 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ import math
5
+ from numbers import Integral
6
+ from collections.abc import Mapping
7
+ from typing import Any, Iterable, Tuple
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Float:
12
+ """A continuous parameter.
13
+
14
+ Args:
15
+ low: Inclusive lower bound. Must be positive when ``log=True``.
16
+ high: Inclusive upper bound.
17
+ log: Sample and adapt in log10 space.
18
+ allow_zero: Also allow an exact zero value as a separate option.
19
+ zero_probability: Initial probability of sampling exact zero.
20
+ """
21
+
22
+ low: float
23
+ high: float
24
+ log: bool = False
25
+ allow_zero: bool = False
26
+ zero_probability: float = 0.15
27
+
28
+ def __post_init__(self) -> None:
29
+ if isinstance(self.low, bool) or isinstance(self.high, bool):
30
+ raise TypeError("Float bounds must be numbers, not booleans.")
31
+ try:
32
+ low, high = float(self.low), float(self.high)
33
+ except (TypeError, ValueError) as exc:
34
+ raise TypeError("Float bounds must be numeric.") from exc
35
+ if not math.isfinite(low) or not math.isfinite(high):
36
+ raise ValueError("Float bounds must be finite.")
37
+ if low >= high:
38
+ raise ValueError("Float requires low < high.")
39
+ if not isinstance(self.log, bool) or not isinstance(self.allow_zero, bool):
40
+ raise TypeError("log and allow_zero must be booleans.")
41
+ if self.log and low <= 0:
42
+ raise ValueError("Float with log=True requires low > 0.")
43
+ if isinstance(self.zero_probability, bool):
44
+ raise TypeError("zero_probability must be numeric.")
45
+ try:
46
+ probability = float(self.zero_probability)
47
+ except (TypeError, ValueError) as exc:
48
+ raise TypeError("zero_probability must be numeric.") from exc
49
+ if not math.isfinite(probability) or not 0 <= probability <= 1:
50
+ raise ValueError("zero_probability must be finite and between 0 and 1.")
51
+ object.__setattr__(self, "low", low)
52
+ object.__setattr__(self, "high", high)
53
+ object.__setattr__(self, "zero_probability", probability)
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Int:
58
+ """An integer parameter sampled on an inclusive stepped range."""
59
+
60
+ low: int
61
+ high: int
62
+ step: int = 1
63
+
64
+ def __post_init__(self) -> None:
65
+ if isinstance(self.low, bool) or isinstance(self.high, bool):
66
+ raise TypeError("Int bounds must be integers, not booleans.")
67
+ if not isinstance(self.low, Integral) or not isinstance(self.high, Integral):
68
+ raise TypeError("Int bounds must be integers.")
69
+ if self.low > self.high:
70
+ raise ValueError("Int requires low <= high.")
71
+ if isinstance(self.step, bool) or not isinstance(self.step, Integral):
72
+ raise TypeError("Int step must be an integer.")
73
+ if self.step < 1:
74
+ raise ValueError("Int step must be >= 1.")
75
+ object.__setattr__(self, "low", int(self.low))
76
+ object.__setattr__(self, "high", int(self.high))
77
+ object.__setattr__(self, "step", int(self.step))
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class Choice:
82
+ """A categorical parameter with one or more possible values."""
83
+
84
+ values: Tuple[Any, ...]
85
+
86
+ def __init__(self, values: Iterable[Any]):
87
+ if isinstance(values, set):
88
+ values = sorted(values, key=repr)
89
+ values = tuple(values)
90
+ if not values:
91
+ raise ValueError("Choice requires at least one value.")
92
+ seen = set()
93
+ for value in values:
94
+ try:
95
+ hash(value)
96
+ except TypeError as exc:
97
+ raise TypeError("Choice values must be hashable.") from exc
98
+ if value in seen:
99
+ raise ValueError("Choice values must be unique.")
100
+ seen.add(value)
101
+ object.__setattr__(self, "values", values)
102
+
103
+
104
+ @dataclass(frozen=True)
105
+ class Bool(Choice):
106
+ """A boolean parameter, equivalent to ``Choice([False, True])``."""
107
+
108
+ def __init__(self):
109
+ object.__setattr__(self, "values", (False, True))
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class Fixed:
114
+ """A fixed value that is passed through unchanged."""
115
+
116
+ value: Any
117
+
118
+
119
+ Parameter = Float | Int | Choice | Fixed
120
+
121
+
122
+ def normalize_parameter(value: Any) -> Parameter:
123
+ """Convert convenient config values and dictionaries into parameter specs.
124
+
125
+ Supported forms:
126
+ * ``Float(...)``, ``Int(...)``, ``Choice(...)``, ``Bool()``, ``Fixed(...)``
127
+ * ``[1, 2, 3]`` or ``("a", "b")`` for categorical choices
128
+ * dictionaries using ``type`` and the matching fields
129
+ * any other scalar as a fixed value
130
+ """
131
+ if isinstance(value, (Float, Int, Choice, Fixed)):
132
+ return value
133
+
134
+ if isinstance(value, Mapping):
135
+ kind = str(value.get("type", "")).lower()
136
+ if kind in {"float", "continuous"}:
137
+ scale = value.get("scale")
138
+ if scale is not None and scale not in {"linear", "log"}:
139
+ raise ValueError("Float scale must be 'linear' or 'log'.")
140
+ return Float(
141
+ low=value["low"],
142
+ high=value["high"],
143
+ log=value.get("log", scale == "log"),
144
+ allow_zero=value.get("allow_zero", False),
145
+ zero_probability=value.get("zero_probability", 0.15),
146
+ )
147
+ if kind in {"int", "integer"}:
148
+ return Int(value["low"], value["high"], value.get("step", 1))
149
+ if kind in {"choice", "categorical", "bool", "boolean"}:
150
+ if kind in {"bool", "boolean"}:
151
+ return Bool()
152
+ return Choice(value["values"])
153
+ if kind == "fixed":
154
+ return Fixed(value["value"])
155
+ raise ValueError(
156
+ "Dictionary parameter specs require type='float', 'int', "
157
+ "'choice', 'bool', or 'fixed'."
158
+ )
159
+
160
+ if isinstance(value, (list, tuple, set, range)):
161
+ return Choice(value)
162
+
163
+ return Fixed(value)
@@ -0,0 +1,356 @@
1
+ Metadata-Version: 2.4
2
+ Name: optican
3
+ Version: 0.1.0
4
+ Summary: Framework-agnostic adaptive hyperparameter optimization with elite-guided search.
5
+ License-Expression: MIT
6
+ Keywords: hyperparameter-optimization,machine-learning,adaptive-search,optimization,pytorch,scikit-learn,tensorflow
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: torch
22
+ Requires-Dist: torch>=2.0; extra == "torch"
23
+ Requires-Dist: numpy>=1.23; extra == "torch"
24
+ Provides-Extra: numpy
25
+ Requires-Dist: numpy>=1.23; extra == "numpy"
26
+ Provides-Extra: sklearn
27
+ Requires-Dist: scikit-learn>=1.2; extra == "sklearn"
28
+ Provides-Extra: tensorflow
29
+ Requires-Dist: tensorflow>=2.12; extra == "tensorflow"
30
+ Provides-Extra: dev
31
+ Requires-Dist: build>=1.2; extra == "dev"
32
+ Requires-Dist: pytest>=8.0; extra == "dev"
33
+ Requires-Dist: ruff>=0.6; extra == "dev"
34
+ Requires-Dist: twine>=5.0; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ # OptiCan
38
+
39
+ OptiCan is a lightweight, framework-agnostic hyperparameter optimization library. It searches continuous, integer, categorical, Boolean, and fixed parameter spaces with adaptive elite-guided refinement.
40
+
41
+ OptiCan does not require PyTorch, TensorFlow, scikit-learn, NumPy, or another machine-learning framework. You provide an objective function that trains and validates your model. OptiCan searches the configuration values passed to that function.
42
+
43
+ The current release is `0.1.0`. The API may change before the first stable release. The search is a heuristic and does not guarantee a global optimum.
44
+
45
+ ## Features
46
+
47
+ - Continuous, log-scaled, integer, categorical, Boolean, and fixed parameters.
48
+ - Adaptive range contraction guided by elite candidate density.
49
+ - Elite-parent mutation that preserves successful parameter combinations.
50
+ - Probability-based categorical refinement.
51
+ - Shared random seeds across candidate evaluations.
52
+ - Optional multi-seed stability scoring.
53
+ - Duplicate configuration avoidance and full trial history.
54
+ - Minimization and maximization objectives.
55
+ - Early stopping and trial limits.
56
+ - No required third-party dependencies.
57
+
58
+ ## Install
59
+
60
+ install it with:
61
+
62
+ ```bash
63
+ pip install optican
64
+ ```
65
+
66
+ For local development:
67
+
68
+ ```bash
69
+ python -m pip install -e ".[dev]"
70
+ pytest
71
+ ```
72
+
73
+ ## Quick start
74
+
75
+ An objective receives a configuration dictionary and optionally a seed. It returns one numeric validation metric. The default direction is `"min"`, which is useful for loss and error metrics.
76
+
77
+ ```python
78
+ from optican import OptiCan, Float, Int, Choice, Bool
79
+
80
+
81
+ def objective(config, seed):
82
+ validation_loss = train_and_validate(
83
+ learning_rate=config["learning_rate"],
84
+ batch_size=config["batch_size"],
85
+ weight_decay=config["weight_decay"],
86
+ optimizer=config["optimizer"],
87
+ use_scheduler=config["use_scheduler"],
88
+ seed=seed,
89
+ )
90
+ return validation_loss
91
+
92
+
93
+ search = OptiCan(
94
+ objective=objective,
95
+ config={
96
+ "learning_rate": Float(1e-5, 1e-2, log=True),
97
+ "batch_size": Choice([32, 64, 128, 256]),
98
+ "weight_decay": Float(1e-7, 1e-2, log=True, allow_zero=True),
99
+ "optimizer": Choice(["AdamW", "Adam", "SGD"]),
100
+ "use_scheduler": Bool(),
101
+ },
102
+ rounds=3,
103
+ ubest=False,
104
+ )
105
+
106
+ last_round_config = search.optimize()
107
+ print(last_round_config)
108
+ ```
109
+
110
+ ## Return behavior
111
+
112
+ `ubest=False` returns the best configuration from the latest completed round that produced a successful trial. This is useful when you want to inspect what the newest refinement round found.
113
+
114
+ `ubest=True` returns a `TuningResult`. Its `best_config`, `best_trial`, and `best_score` refer to the best result across all rounds.
115
+
116
+ The full result is available as `search.result` in both modes. It keeps the global best and the latest successful round best:
117
+
118
+ ```python
119
+ print(search.result.best_config)
120
+ print(search.result.best_score)
121
+ print(search.result.last_round_best_config)
122
+ print(search.result.last_round_best_score)
123
+ print(search.result.summary())
124
+
125
+ for trial in search.result.trials:
126
+ print(trial.config, trial.mean_score, trial.std_score, trial.error)
127
+ ```
128
+
129
+ If the latest round has no successful trials, OptiCan uses the best result from the latest earlier round that had a successful trial. A fixed-only search or an empty configuration is evaluated once.
130
+
131
+ ## Search-space parameters
132
+
133
+ Use helper classes for explicit search spaces:
134
+
135
+ | Type | Example | Behavior |
136
+ |---|---|---|
137
+ | Float | `Float(1e-5, 1e-2)` | Samples a continuous range |
138
+ | Log float | `Float(1e-5, 1e-2, log=True)` | Samples uniformly in log10 space |
139
+ | Zero-capable float | `Float(1e-7, 1e-2, log=True, allow_zero=True)` | Adds exact zero as a separate option |
140
+ | Integer | `Int(16, 256, step=16)` | Samples integer values on a stepped range |
141
+ | Categorical | `Choice(["Adam", "AdamW"])` | Learns category probabilities |
142
+ | Boolean | `Bool()` | Learns probabilities for `True` and `False` |
143
+ | Fixed | `Fixed("gelu")` | Keeps a value unchanged |
144
+
145
+ A list or tuple is treated as a categorical choice. Any other scalar is treated as a fixed value. An empty `config={}` is valid and evaluates the objective once with an empty configuration.
146
+
147
+ Compact dictionary definitions are also supported:
148
+
149
+ ```python
150
+ config = {
151
+ "learning_rate": {
152
+ "type": "float",
153
+ "low": 1e-5,
154
+ "high": 1e-2,
155
+ "log": True,
156
+ },
157
+ "depth": {"type": "int", "low": 2, "high": 12},
158
+ "optimizer": {"type": "choice", "values": ["Adam", "AdamW"]},
159
+ "use_dropout": {"type": "bool"},
160
+ "activation": ["relu", "gelu", "silu"],
161
+ "device": "cuda",
162
+ }
163
+ ```
164
+
165
+ ## Options
166
+
167
+ | Option | Default | Meaning |
168
+ |---|---:|---|
169
+ | `rounds` | `3` | Total search rounds, including the initial round |
170
+ | `initial_candidates` | `24` | Configurations sampled in the first round |
171
+ | `candidates_per_round` | `12` | New configurations in each later round |
172
+ | `elite_size` | `20` | Top configurations used to guide refinement |
173
+ | `seeds` | `1` | Number of shared seeds used per configuration |
174
+ | `seed` | `42` | Base seed, later seeds increase by one |
175
+ | `direction` | `"min"` | Use `"max"` for metrics such as accuracy or F1 |
176
+ | `stability_penalty` | `0.25` | Penalty for score variation across seeds |
177
+ | `mutation_rate` | `0.70` | Chance of mutating each parameter in a child |
178
+ | `exploration_mix` | `0.20` | Fraction sampled independently of elite parents |
179
+ | `categorical_exploration` | `0.15` | Keeps category sampling from collapsing too early |
180
+ | `shrink_fraction` | `0.20` | Fraction of the active numeric range contracted per round |
181
+ | `min_range_fraction` | `0.05` | Minimum range width relative to its initial width |
182
+ | `max_trials` | `None` | Optional cap on evaluated configurations |
183
+ | `patience_rounds` | `0` | Stop after this many stagnant rounds, zero disables it |
184
+ | `min_delta` | `0.0` | Minimum improvement needed to reset patience |
185
+ | `ubest` | `False` | Selects the latest-round config or returns the full global result |
186
+ | `verbose` | `True` | Prints progress while evaluating candidates |
187
+ | `catch_exceptions` | `True` | Records failed evaluations and continues |
188
+
189
+ Use `seeds=1` for faster tests. Increase it to `3` or `5` for more stable comparisons. The same seed set is used for every configuration.
190
+
191
+ OptiCan evaluates candidates sequentially by default. This avoids global random-seed interference and unexpected GPU memory use across different frameworks. Reduce candidate counts, use `max_trials`, or add early stopping inside the objective to reduce evaluation time.
192
+
193
+ ## Metric formulas
194
+
195
+ A separate `metric="t/a"` option is not needed. The objective function already provides a flexible way to calculate any metric. Compute the values your formula needs and return the result.
196
+
197
+ ```python
198
+ def objective(config, seed):
199
+ predictions = train_and_predict(config, seed)
200
+ t = count_true_predictions(predictions)
201
+ a = count_all_predictions(predictions)
202
+ return t / max(a, 1)
203
+ ```
204
+
205
+ The objective can calculate a single metric, combine several metrics, or call an existing scoring function. OptiCan only needs the final numeric result. Set `direction="max"` when higher values are better.
206
+
207
+ ## PyTorch example
208
+
209
+ OptiCan does not create or manage models itself. Put model creation, training, early stopping, and validation inside the objective. Replace `Model` and the data variables with your own objects.
210
+
211
+ ```python
212
+ import random
213
+ import numpy as np
214
+ import torch
215
+ import torch.nn as nn
216
+ from torch.utils.data import DataLoader, TensorDataset
217
+
218
+ from optican import OptiCan, Float, Choice, Bool
219
+
220
+
221
+ def objective(config, seed):
222
+ random.seed(seed)
223
+ np.random.seed(seed)
224
+ torch.manual_seed(seed)
225
+ if torch.cuda.is_available():
226
+ torch.cuda.manual_seed_all(seed)
227
+
228
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
229
+ model = Model().to(device)
230
+ optimizer_class = getattr(torch.optim, config["optimizer"])
231
+ optimizer = optimizer_class(
232
+ model.parameters(),
233
+ lr=config["learning_rate"],
234
+ weight_decay=config["weight_decay"],
235
+ )
236
+ loss_fn = nn.CrossEntropyLoss()
237
+ scheduler = None
238
+ if config["use_scheduler"]:
239
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=20)
240
+ loader = DataLoader(
241
+ TensorDataset(X_train, y_train),
242
+ batch_size=config["batch_size"],
243
+ shuffle=True,
244
+ )
245
+
246
+ best_val_loss = float("inf")
247
+ for _ in range(20):
248
+ model.train()
249
+ for x, y in loader:
250
+ x, y = x.to(device), y.to(device)
251
+ optimizer.zero_grad(set_to_none=True)
252
+ loss = loss_fn(model(x), y)
253
+ loss.backward()
254
+ optimizer.step()
255
+
256
+ model.eval()
257
+ with torch.no_grad():
258
+ val_loss = loss_fn(
259
+ model(X_valid.to(device)),
260
+ y_valid.to(device),
261
+ ).item()
262
+ best_val_loss = min(best_val_loss, val_loss)
263
+ if scheduler is not None:
264
+ scheduler.step()
265
+
266
+ return best_val_loss
267
+
268
+
269
+ search = OptiCan(
270
+ objective,
271
+ config={
272
+ "learning_rate": Float(1e-5, 3e-3, log=True),
273
+ "weight_decay": Float(1e-7, 1e-2, log=True, allow_zero=True),
274
+ "batch_size": Choice([32, 64, 128, 256]),
275
+ "optimizer": Choice(["AdamW", "Adam"]),
276
+ "use_scheduler": Bool(),
277
+ },
278
+ rounds=3,
279
+ seeds=3,
280
+ ubest=True,
281
+ )
282
+
283
+ result = search.optimize()
284
+ print(result.best_config)
285
+ print(result.best_score)
286
+ ```
287
+
288
+ ## Scikit-learn example
289
+
290
+ ```python
291
+ from sklearn.ensemble import RandomForestClassifier
292
+ from sklearn.model_selection import cross_val_score
293
+ from optican import OptiCan, Int, Choice
294
+
295
+
296
+ def objective(config, seed):
297
+ estimator = RandomForestClassifier(
298
+ n_estimators=config["n_estimators"],
299
+ max_depth=config["max_depth"],
300
+ criterion=config["criterion"],
301
+ random_state=seed,
302
+ n_jobs=-1,
303
+ )
304
+ return cross_val_score(
305
+ estimator, X, y, cv=5, scoring="accuracy", n_jobs=-1
306
+ ).mean()
307
+
308
+
309
+ search = OptiCan(
310
+ objective,
311
+ config={
312
+ "n_estimators": Int(100, 600, step=50),
313
+ "max_depth": Choice([None, 5, 10, 20, 30]),
314
+ "criterion": Choice(["gini", "entropy", "log_loss"]),
315
+ },
316
+ direction="max",
317
+ rounds=3,
318
+ )
319
+
320
+ best_config = search.optimize()
321
+ ```
322
+
323
+ ## How the algorithm works
324
+
325
+ 1. Initial configurations are sampled from the parameter distributions.
326
+ 2. Every configuration is evaluated with the same seed set.
327
+ 3. Successful trials are ranked by their mean metric and optional stability penalty.
328
+ 4. Numeric ranges contract toward elite regions, with more contraction on the side with fewer elite samples.
329
+ 5. Categorical probabilities increase for values that appear more often among elite trials.
330
+ 6. New configurations mutate successful parent configurations, preserving useful parameter combinations.
331
+ 7. Every trial is kept, so the global best can be selected across all rounds.
332
+
333
+ This is an adaptive heuristic. It can miss a global optimum, especially with narrow ranges, noisy objectives, strong parameter interactions, or too few evaluations. Use a suitable evaluation budget and validation split.
334
+
335
+ ## Reproducibility and objective requirements
336
+
337
+ - Return one finite numeric validation metric.
338
+ - Do not use the test set to choose hyperparameters. Reserve it for final evaluation.
339
+ - Use the supplied seed for model initialization, data shuffling, and randomized preprocessing.
340
+ - OptiCan seeds Python and seeds NumPy, PyTorch, and TensorFlow only when they are already imported.
341
+ - Some GPU operations may remain nondeterministic unless the framework is configured for deterministic execution.
342
+ - Add early stopping inside the objective when the training loop supports it.
343
+
344
+ ## Development
345
+
346
+ ```bash
347
+ python -m pip install -e ".[dev]"
348
+ pytest
349
+ ruff check src tests examples
350
+ python -m build
351
+ python -m twine check dist/*
352
+ ```
353
+
354
+ ## License
355
+
356
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,8 @@
1
+ optican/__init__.py,sha256=HE5L50Wptzk-OliFXXURY_ZuW5exSSL1P4nKdEk_OyQ,264
2
+ optican/optimizer.py,sha256=PfxnYVJzgKy91oRtfiWYCbEp8FbZU6gJVCl0csl-JmA,33592
3
+ optican/space.py,sha256=p5BBVJsx0aZviE4sBr9yUmf7YQPnKRfqiPF555-kDjU,5950
4
+ optican-0.1.0.dist-info/licenses/LICENSE,sha256=bkM5841uaEjafnjbtYPYVCP3KNYpa8QrBxD8hZow7Sk,1077
5
+ optican-0.1.0.dist-info/METADATA,sha256=tyyhFPsxHPTDfvvPNUUmMQpP5p_5B81_Jh_XanVv6WQ,13327
6
+ optican-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ optican-0.1.0.dist-info/top_level.txt,sha256=37vYNUQ8LQXkBGTXg7LHmCGgmY5nKwSAMmrDTIFZ7ZI,8
8
+ optican-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OptiCan contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ optican