|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT license. |
| 3 | + |
| 4 | +"""Progressive schedule controller and state models for Greedy Coordinate Gradient (GCG) attacks.""" |
| 5 | + |
| 6 | +import logging |
| 7 | +from dataclasses import dataclass |
| 8 | +from enum import Enum, auto |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class ProgressiveScheduleState: |
| 15 | + """ |
| 16 | + Typed schedule state for ``ProgressiveMultiPromptAttack``. |
| 17 | +
|
| 18 | + Tracks how many goals and workers have been admitted so far, together with |
| 19 | + the shared step counter and the loss carried between progressive rounds. |
| 20 | + Exposed as ``ProgressiveMultiPromptAttack.last_schedule_state`` after a call |
| 21 | + to ``ProgressiveMultiPromptAttack.run``. |
| 22 | + """ |
| 23 | + |
| 24 | + goals_admitted: int |
| 25 | + workers_admitted: int |
| 26 | + steps_completed: int = 0 |
| 27 | + loss: float = float("inf") |
| 28 | + stop_inner_on_success: bool = False |
| 29 | + |
| 30 | + |
| 31 | +class ScheduleTransitionAction(Enum): |
| 32 | + """Action to take following an inner attack result in progressive scheduling.""" |
| 33 | + |
| 34 | + CONTINUE = auto() |
| 35 | + FINALIZE_AND_STOP = auto() |
| 36 | + |
| 37 | + |
| 38 | +class ProgressiveScheduleController: |
| 39 | + """Encapsulates progressive admission, step budget scheduling, and state transitions.""" |
| 40 | + |
| 41 | + def __init__( |
| 42 | + self, |
| 43 | + *, |
| 44 | + total_goals: int, |
| 45 | + total_workers: int, |
| 46 | + progressive_goals: bool = True, |
| 47 | + progressive_models: bool = True, |
| 48 | + n_steps: int = 1000, |
| 49 | + control_weight: float | None = None, |
| 50 | + incr_control: bool = True, |
| 51 | + stop_on_success: bool = True, |
| 52 | + verbose: bool = True, |
| 53 | + ) -> None: |
| 54 | + """ |
| 55 | + Initialize the progressive schedule controller. |
| 56 | +
|
| 57 | + Args: |
| 58 | + total_goals: Total number of attack goals available for admission. |
| 59 | + total_workers: Total number of model workers available for admission. |
| 60 | + progressive_goals: Whether goals are admitted progressively one at a time. |
| 61 | + progressive_models: Whether models/workers are admitted progressively one at a time. |
| 62 | + n_steps: Total step budget across all progressive rounds. |
| 63 | + control_weight: Current control weight, or None. |
| 64 | + incr_control: Whether to increment control weight when all goals/models are admitted. |
| 65 | + stop_on_success: Whether to finalize and stop when fully admitted and success is achieved. |
| 66 | + verbose: Whether to log control weight updates. |
| 67 | +
|
| 68 | + Raises: |
| 69 | + ValueError: If total_goals or total_workers is not positive. |
| 70 | + """ |
| 71 | + if total_goals <= 0: |
| 72 | + raise ValueError(f"total_goals must be positive, got {total_goals}") |
| 73 | + if total_workers <= 0: |
| 74 | + raise ValueError(f"total_workers must be positive, got {total_workers}") |
| 75 | + |
| 76 | + self._total_goals = total_goals |
| 77 | + self._total_workers = total_workers |
| 78 | + self._n_steps = n_steps |
| 79 | + self._control_weight = control_weight |
| 80 | + self._incr_control = incr_control |
| 81 | + self._stop_on_success = stop_on_success |
| 82 | + self._verbose = verbose |
| 83 | + |
| 84 | + self._state = ProgressiveScheduleState( |
| 85 | + goals_admitted=1 if progressive_goals else total_goals, |
| 86 | + workers_admitted=1 if progressive_models else total_workers, |
| 87 | + stop_inner_on_success=progressive_goals, |
| 88 | + ) |
| 89 | + self._loss_is_measured = False |
| 90 | + |
| 91 | + @property |
| 92 | + def state(self) -> ProgressiveScheduleState: |
| 93 | + """The current progressive schedule state.""" |
| 94 | + return self._state |
| 95 | + |
| 96 | + @property |
| 97 | + def is_complete(self) -> bool: |
| 98 | + """Whether the overall step budget has been exhausted.""" |
| 99 | + return self._state.steps_completed >= self._n_steps |
| 100 | + |
| 101 | + @property |
| 102 | + def remaining_steps(self) -> int: |
| 103 | + """The remaining number of optimization steps in the budget.""" |
| 104 | + return max(0, self._n_steps - self._state.steps_completed) |
| 105 | + |
| 106 | + @property |
| 107 | + def active_goal_count(self) -> int: |
| 108 | + """The number of currently admitted goals.""" |
| 109 | + return self._state.goals_admitted |
| 110 | + |
| 111 | + @property |
| 112 | + def active_worker_count(self) -> int: |
| 113 | + """The number of currently admitted workers.""" |
| 114 | + return self._state.workers_admitted |
| 115 | + |
| 116 | + @property |
| 117 | + def control_weight(self) -> float | None: |
| 118 | + """The current control weight.""" |
| 119 | + return self._control_weight |
| 120 | + |
| 121 | + @property |
| 122 | + def is_fully_admitted(self) -> bool: |
| 123 | + """Whether all goals and workers have been admitted.""" |
| 124 | + return self._state.goals_admitted == self._total_goals and self._state.workers_admitted == self._total_workers |
| 125 | + |
| 126 | + def before_inner_run(self) -> None: |
| 127 | + """Prepare schedule state immediately before launching an inner attack.""" |
| 128 | + if self.is_fully_admitted: |
| 129 | + self._state.stop_inner_on_success = False |
| 130 | + |
| 131 | + def advance_after_inner_run( |
| 132 | + self, |
| 133 | + *, |
| 134 | + inner_loss: float, |
| 135 | + inner_steps: int, |
| 136 | + ) -> ScheduleTransitionAction: |
| 137 | + """ |
| 138 | + Update schedule state and determine the next action after an inner attack round completes. |
| 139 | +
|
| 140 | + Args: |
| 141 | + inner_loss: Final loss reported by the inner attack. |
| 142 | + inner_steps: Number of steps completed by the inner attack. |
| 143 | +
|
| 144 | + Returns: |
| 145 | + ScheduleTransitionAction indicating whether to continue or finalize and stop. |
| 146 | + """ |
| 147 | + self._state.loss = inner_loss |
| 148 | + self._loss_is_measured = True |
| 149 | + self._state.steps_completed += inner_steps |
| 150 | + |
| 151 | + prepare_next_round = self._state.steps_completed < self._n_steps |
| 152 | + |
| 153 | + if self._state.goals_admitted < self._total_goals: |
| 154 | + if prepare_next_round: |
| 155 | + self._state.goals_admitted += 1 |
| 156 | + self._state.loss = float("inf") |
| 157 | + self._loss_is_measured = False |
| 158 | + return ScheduleTransitionAction.CONTINUE |
| 159 | + |
| 160 | + if self._state.workers_admitted < self._total_workers: |
| 161 | + if prepare_next_round: |
| 162 | + self._state.workers_admitted += 1 |
| 163 | + self._state.loss = float("inf") |
| 164 | + self._loss_is_measured = False |
| 165 | + return ScheduleTransitionAction.CONTINUE |
| 166 | + |
| 167 | + if self._state.workers_admitted == self._total_workers and self._stop_on_success: |
| 168 | + return ScheduleTransitionAction.FINALIZE_AND_STOP |
| 169 | + |
| 170 | + if prepare_next_round and isinstance(self._control_weight, (int, float)) and self._incr_control: |
| 171 | + if self._control_weight <= 0.09: |
| 172 | + self._control_weight += 0.01 |
| 173 | + self._state.loss = float("inf") |
| 174 | + self._loss_is_measured = False |
| 175 | + if self._verbose: |
| 176 | + logger.info(f"Control weight increased to {self._control_weight:.5}") |
| 177 | + else: |
| 178 | + self._state.stop_inner_on_success = False |
| 179 | + |
| 180 | + return ScheduleTransitionAction.CONTINUE |
| 181 | + |
| 182 | + def validate_post_run(self) -> None: |
| 183 | + """ |
| 184 | + Validate post-run invariants. |
| 185 | +
|
| 186 | + Raises: |
| 187 | + AssertionError: If steps were completed but schedule.loss was never updated by an inner run. |
| 188 | + """ |
| 189 | + if self._state.steps_completed > 0: |
| 190 | + assert self._loss_is_measured, "schedule.loss was never updated by the inner run" |
0 commit comments