ZTWHHH commited on
Commit
dded22d
·
verified ·
1 Parent(s): f2cfabe

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. parrot/lib/python3.10/site-packages/scipy/interpolate/interpnd.cpython-310-x86_64-linux-gnu.so +3 -0
  3. parrot/lib/python3.10/site-packages/scipy/linalg/tests/data/carex_20_data.npz +3 -0
  4. parrot/lib/python3.10/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz +3 -0
  5. parrot/lib/python3.10/site-packages/scipy/optimize/_linprog_highs.py +440 -0
  6. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/bvls.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/trf_linear.cpython-310.pyc +0 -0
  8. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/bvls.py +183 -0
  9. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/common.py +733 -0
  10. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/dogbox.py +331 -0
  11. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/least_squares.py +967 -0
  12. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/lsq_linear.py +362 -0
  13. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/trf.py +560 -0
  14. parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/trf_linear.py +249 -0
  15. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-310.pyc +0 -0
  16. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-310.pyc +0 -0
  17. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-310.pyc +0 -0
  18. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py +231 -0
  19. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py +564 -0
  20. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/projections.py +407 -0
  21. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py +637 -0
  22. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/report.py +51 -0
  23. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py +0 -0
  24. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  25. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-310.pyc +0 -0
  26. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-310.pyc +0 -0
  27. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py +296 -0
  28. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py +214 -0
  29. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py +645 -0
  30. parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py +34 -0
  31. vllm/lib/python3.10/site-packages/transformers/generation/__pycache__/logits_process.cpython-310.pyc +3 -0
  32. vllm/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils.cpython-310.pyc +3 -0
  33. vllm/lib/python3.10/site-packages/transformers/models/bloom/__init__.py +29 -0
  34. vllm/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-310.pyc +0 -0
  35. vllm/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-310.pyc +0 -0
  36. vllm/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-310.pyc +0 -0
  37. vllm/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/transformers/models/bloom/configuration_bloom.py +237 -0
  39. vllm/lib/python3.10/site-packages/transformers/models/bloom/modeling_bloom.py +1398 -0
  40. vllm/lib/python3.10/site-packages/transformers/models/bloom/tokenization_bloom_fast.py +152 -0
  41. vllm/lib/python3.10/site-packages/transformers/models/cpmant/__init__.py +28 -0
  42. vllm/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/__init__.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/transformers/models/cpmant/modeling_cpmant.py +860 -0
  47. vllm/lib/python3.10/site-packages/transformers/models/cpmant/tokenization_cpmant.py +270 -0
  48. vllm/lib/python3.10/site-packages/transformers/models/deformable_detr/__init__.py +32 -0
  49. vllm/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/__init__.cpython-310.pyc +0 -0
  50. vllm/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -1635,3 +1635,6 @@ parrot/lib/python3.10/site-packages/scipy/special/_ellip_harm_2.cpython-310-x86_
1635
  parrot/lib/python3.10/site-packages/pandas/_libs/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1636
  wemm/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.so.11.2 filter=lfs diff=lfs merge=lfs -text
1637
  vllm/lib/python3.10/site-packages/fastrlock/rlock.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
1635
  parrot/lib/python3.10/site-packages/pandas/_libs/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1636
  wemm/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc.so.11.2 filter=lfs diff=lfs merge=lfs -text
1637
  vllm/lib/python3.10/site-packages/fastrlock/rlock.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1638
+ parrot/lib/python3.10/site-packages/scipy/interpolate/interpnd.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1639
+ vllm/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1640
+ vllm/lib/python3.10/site-packages/transformers/generation/__pycache__/logits_process.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
parrot/lib/python3.10/site-packages/scipy/interpolate/interpnd.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:858919e18e295550cd7be75e89651b5d12ad97a9e2d3c540da006b42c42ac19c
3
+ size 458776
parrot/lib/python3.10/site-packages/scipy/linalg/tests/data/carex_20_data.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14e222d34a7118c7284a1675c6feceee77b84df951a5c6ba2a5ee9ff3054fa1d
3
+ size 31231
parrot/lib/python3.10/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3dfab451d9d5c20243e0ed85cd8b6c9657669fb9a0f83b5be165585783d55b5
3
+ size 2164
parrot/lib/python3.10/site-packages/scipy/optimize/_linprog_highs.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HiGHS Linear Optimization Methods
2
+
3
+ Interface to HiGHS linear optimization software.
4
+ https://highs.dev/
5
+
6
+ .. versionadded:: 1.5.0
7
+
8
+ References
9
+ ----------
10
+ .. [1] Q. Huangfu and J.A.J. Hall. "Parallelizing the dual revised simplex
11
+ method." Mathematical Programming Computation, 10 (1), 119-142,
12
+ 2018. DOI: 10.1007/s12532-017-0130-5
13
+
14
+ """
15
+
16
+ import inspect
17
+ import numpy as np
18
+ from ._optimize import OptimizeWarning, OptimizeResult
19
+ from warnings import warn
20
+ from ._highs._highs_wrapper import _highs_wrapper
21
+ from ._highs._highs_constants import (
22
+ CONST_INF,
23
+ MESSAGE_LEVEL_NONE,
24
+ HIGHS_OBJECTIVE_SENSE_MINIMIZE,
25
+
26
+ MODEL_STATUS_NOTSET,
27
+ MODEL_STATUS_LOAD_ERROR,
28
+ MODEL_STATUS_MODEL_ERROR,
29
+ MODEL_STATUS_PRESOLVE_ERROR,
30
+ MODEL_STATUS_SOLVE_ERROR,
31
+ MODEL_STATUS_POSTSOLVE_ERROR,
32
+ MODEL_STATUS_MODEL_EMPTY,
33
+ MODEL_STATUS_OPTIMAL,
34
+ MODEL_STATUS_INFEASIBLE,
35
+ MODEL_STATUS_UNBOUNDED_OR_INFEASIBLE,
36
+ MODEL_STATUS_UNBOUNDED,
37
+ MODEL_STATUS_REACHED_DUAL_OBJECTIVE_VALUE_UPPER_BOUND
38
+ as MODEL_STATUS_RDOVUB,
39
+ MODEL_STATUS_REACHED_OBJECTIVE_TARGET,
40
+ MODEL_STATUS_REACHED_TIME_LIMIT,
41
+ MODEL_STATUS_REACHED_ITERATION_LIMIT,
42
+
43
+ HIGHS_SIMPLEX_STRATEGY_DUAL,
44
+
45
+ HIGHS_SIMPLEX_CRASH_STRATEGY_OFF,
46
+
47
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_CHOOSE,
48
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_DANTZIG,
49
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_DEVEX,
50
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_STEEPEST_EDGE,
51
+ )
52
+ from scipy.sparse import csc_matrix, vstack, issparse
53
+
54
+
55
+ def _highs_to_scipy_status_message(highs_status, highs_message):
56
+ """Converts HiGHS status number/message to SciPy status number/message"""
57
+
58
+ scipy_statuses_messages = {
59
+ None: (4, "HiGHS did not provide a status code. "),
60
+ MODEL_STATUS_NOTSET: (4, ""),
61
+ MODEL_STATUS_LOAD_ERROR: (4, ""),
62
+ MODEL_STATUS_MODEL_ERROR: (2, ""),
63
+ MODEL_STATUS_PRESOLVE_ERROR: (4, ""),
64
+ MODEL_STATUS_SOLVE_ERROR: (4, ""),
65
+ MODEL_STATUS_POSTSOLVE_ERROR: (4, ""),
66
+ MODEL_STATUS_MODEL_EMPTY: (4, ""),
67
+ MODEL_STATUS_RDOVUB: (4, ""),
68
+ MODEL_STATUS_REACHED_OBJECTIVE_TARGET: (4, ""),
69
+ MODEL_STATUS_OPTIMAL: (0, "Optimization terminated successfully. "),
70
+ MODEL_STATUS_REACHED_TIME_LIMIT: (1, "Time limit reached. "),
71
+ MODEL_STATUS_REACHED_ITERATION_LIMIT: (1, "Iteration limit reached. "),
72
+ MODEL_STATUS_INFEASIBLE: (2, "The problem is infeasible. "),
73
+ MODEL_STATUS_UNBOUNDED: (3, "The problem is unbounded. "),
74
+ MODEL_STATUS_UNBOUNDED_OR_INFEASIBLE: (4, "The problem is unbounded "
75
+ "or infeasible. ")}
76
+ unrecognized = (4, "The HiGHS status code was not recognized. ")
77
+ scipy_status, scipy_message = (
78
+ scipy_statuses_messages.get(highs_status, unrecognized))
79
+ scipy_message = (f"{scipy_message}"
80
+ f"(HiGHS Status {highs_status}: {highs_message})")
81
+ return scipy_status, scipy_message
82
+
83
+
84
+ def _replace_inf(x):
85
+ # Replace `np.inf` with CONST_INF
86
+ infs = np.isinf(x)
87
+ with np.errstate(invalid="ignore"):
88
+ x[infs] = np.sign(x[infs])*CONST_INF
89
+ return x
90
+
91
+
92
+ def _convert_to_highs_enum(option, option_str, choices):
93
+ # If option is in the choices we can look it up, if not use
94
+ # the default value taken from function signature and warn:
95
+ try:
96
+ return choices[option.lower()]
97
+ except AttributeError:
98
+ return choices[option]
99
+ except KeyError:
100
+ sig = inspect.signature(_linprog_highs)
101
+ default_str = sig.parameters[option_str].default
102
+ warn(f"Option {option_str} is {option}, but only values in "
103
+ f"{set(choices.keys())} are allowed. Using default: "
104
+ f"{default_str}.",
105
+ OptimizeWarning, stacklevel=3)
106
+ return choices[default_str]
107
+
108
+
109
+ def _linprog_highs(lp, solver, time_limit=None, presolve=True,
110
+ disp=False, maxiter=None,
111
+ dual_feasibility_tolerance=None,
112
+ primal_feasibility_tolerance=None,
113
+ ipm_optimality_tolerance=None,
114
+ simplex_dual_edge_weight_strategy=None,
115
+ mip_rel_gap=None,
116
+ mip_max_nodes=None,
117
+ **unknown_options):
118
+ r"""
119
+ Solve the following linear programming problem using one of the HiGHS
120
+ solvers:
121
+
122
+ User-facing documentation is in _linprog_doc.py.
123
+
124
+ Parameters
125
+ ----------
126
+ lp : _LPProblem
127
+ A ``scipy.optimize._linprog_util._LPProblem`` ``namedtuple``.
128
+ solver : "ipm" or "simplex" or None
129
+ Which HiGHS solver to use. If ``None``, "simplex" will be used.
130
+
131
+ Options
132
+ -------
133
+ maxiter : int
134
+ The maximum number of iterations to perform in either phase. For
135
+ ``solver='ipm'``, this does not include the number of crossover
136
+ iterations. Default is the largest possible value for an ``int``
137
+ on the platform.
138
+ disp : bool
139
+ Set to ``True`` if indicators of optimization status are to be printed
140
+ to the console each iteration; default ``False``.
141
+ time_limit : float
142
+ The maximum time in seconds allotted to solve the problem; default is
143
+ the largest possible value for a ``double`` on the platform.
144
+ presolve : bool
145
+ Presolve attempts to identify trivial infeasibilities,
146
+ identify trivial unboundedness, and simplify the problem before
147
+ sending it to the main solver. It is generally recommended
148
+ to keep the default setting ``True``; set to ``False`` if presolve is
149
+ to be disabled.
150
+ dual_feasibility_tolerance : double
151
+ Dual feasibility tolerance. Default is 1e-07.
152
+ The minimum of this and ``primal_feasibility_tolerance``
153
+ is used for the feasibility tolerance when ``solver='ipm'``.
154
+ primal_feasibility_tolerance : double
155
+ Primal feasibility tolerance. Default is 1e-07.
156
+ The minimum of this and ``dual_feasibility_tolerance``
157
+ is used for the feasibility tolerance when ``solver='ipm'``.
158
+ ipm_optimality_tolerance : double
159
+ Optimality tolerance for ``solver='ipm'``. Default is 1e-08.
160
+ Minimum possible value is 1e-12 and must be smaller than the largest
161
+ possible value for a ``double`` on the platform.
162
+ simplex_dual_edge_weight_strategy : str (default: None)
163
+ Strategy for simplex dual edge weights. The default, ``None``,
164
+ automatically selects one of the following.
165
+
166
+ ``'dantzig'`` uses Dantzig's original strategy of choosing the most
167
+ negative reduced cost.
168
+
169
+ ``'devex'`` uses the strategy described in [15]_.
170
+
171
+ ``steepest`` uses the exact steepest edge strategy as described in
172
+ [16]_.
173
+
174
+ ``'steepest-devex'`` begins with the exact steepest edge strategy
175
+ until the computation is too costly or inexact and then switches to
176
+ the devex method.
177
+
178
+ Currently, using ``None`` always selects ``'steepest-devex'``, but this
179
+ may change as new options become available.
180
+
181
+ mip_max_nodes : int
182
+ The maximum number of nodes allotted to solve the problem; default is
183
+ the largest possible value for a ``HighsInt`` on the platform.
184
+ Ignored if not using the MIP solver.
185
+ unknown_options : dict
186
+ Optional arguments not used by this particular solver. If
187
+ ``unknown_options`` is non-empty, a warning is issued listing all
188
+ unused options.
189
+
190
+ Returns
191
+ -------
192
+ sol : dict
193
+ A dictionary consisting of the fields:
194
+
195
+ x : 1D array
196
+ The values of the decision variables that minimizes the
197
+ objective function while satisfying the constraints.
198
+ fun : float
199
+ The optimal value of the objective function ``c @ x``.
200
+ slack : 1D array
201
+ The (nominally positive) values of the slack,
202
+ ``b_ub - A_ub @ x``.
203
+ con : 1D array
204
+ The (nominally zero) residuals of the equality constraints,
205
+ ``b_eq - A_eq @ x``.
206
+ success : bool
207
+ ``True`` when the algorithm succeeds in finding an optimal
208
+ solution.
209
+ status : int
210
+ An integer representing the exit status of the algorithm.
211
+
212
+ ``0`` : Optimization terminated successfully.
213
+
214
+ ``1`` : Iteration or time limit reached.
215
+
216
+ ``2`` : Problem appears to be infeasible.
217
+
218
+ ``3`` : Problem appears to be unbounded.
219
+
220
+ ``4`` : The HiGHS solver ran into a problem.
221
+
222
+ message : str
223
+ A string descriptor of the exit status of the algorithm.
224
+ nit : int
225
+ The total number of iterations performed.
226
+ For ``solver='simplex'``, this includes iterations in all
227
+ phases. For ``solver='ipm'``, this does not include
228
+ crossover iterations.
229
+ crossover_nit : int
230
+ The number of primal/dual pushes performed during the
231
+ crossover routine for ``solver='ipm'``. This is ``0``
232
+ for ``solver='simplex'``.
233
+ ineqlin : OptimizeResult
234
+ Solution and sensitivity information corresponding to the
235
+ inequality constraints, `b_ub`. A dictionary consisting of the
236
+ fields:
237
+
238
+ residual : np.ndnarray
239
+ The (nominally positive) values of the slack variables,
240
+ ``b_ub - A_ub @ x``. This quantity is also commonly
241
+ referred to as "slack".
242
+
243
+ marginals : np.ndarray
244
+ The sensitivity (partial derivative) of the objective
245
+ function with respect to the right-hand side of the
246
+ inequality constraints, `b_ub`.
247
+
248
+ eqlin : OptimizeResult
249
+ Solution and sensitivity information corresponding to the
250
+ equality constraints, `b_eq`. A dictionary consisting of the
251
+ fields:
252
+
253
+ residual : np.ndarray
254
+ The (nominally zero) residuals of the equality constraints,
255
+ ``b_eq - A_eq @ x``.
256
+
257
+ marginals : np.ndarray
258
+ The sensitivity (partial derivative) of the objective
259
+ function with respect to the right-hand side of the
260
+ equality constraints, `b_eq`.
261
+
262
+ lower, upper : OptimizeResult
263
+ Solution and sensitivity information corresponding to the
264
+ lower and upper bounds on decision variables, `bounds`.
265
+
266
+ residual : np.ndarray
267
+ The (nominally positive) values of the quantity
268
+ ``x - lb`` (lower) or ``ub - x`` (upper).
269
+
270
+ marginals : np.ndarray
271
+ The sensitivity (partial derivative) of the objective
272
+ function with respect to the lower and upper
273
+ `bounds`.
274
+
275
+ mip_node_count : int
276
+ The number of subproblems or "nodes" solved by the MILP
277
+ solver. Only present when `integrality` is not `None`.
278
+
279
+ mip_dual_bound : float
280
+ The MILP solver's final estimate of the lower bound on the
281
+ optimal solution. Only present when `integrality` is not
282
+ `None`.
283
+
284
+ mip_gap : float
285
+ The difference between the final objective function value
286
+ and the final dual bound, scaled by the final objective
287
+ function value. Only present when `integrality` is not
288
+ `None`.
289
+
290
+ Notes
291
+ -----
292
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
293
+ `marginals`, or partial derivatives of the objective function with respect
294
+ to the right-hand side of each constraint. These partial derivatives are
295
+ also referred to as "Lagrange multipliers", "dual values", and
296
+ "shadow prices". The sign convention of `marginals` is opposite that
297
+ of Lagrange multipliers produced by many nonlinear solvers.
298
+
299
+ References
300
+ ----------
301
+ .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
302
+ Mathematical programming 5.1 (1973): 1-28.
303
+ .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
304
+ simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
305
+ """
306
+ if unknown_options:
307
+ message = (f"Unrecognized options detected: {unknown_options}. "
308
+ "These will be passed to HiGHS verbatim.")
309
+ warn(message, OptimizeWarning, stacklevel=3)
310
+
311
+ # Map options to HiGHS enum values
312
+ simplex_dual_edge_weight_strategy_enum = _convert_to_highs_enum(
313
+ simplex_dual_edge_weight_strategy,
314
+ 'simplex_dual_edge_weight_strategy',
315
+ choices={'dantzig': HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_DANTZIG,
316
+ 'devex': HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_DEVEX,
317
+ 'steepest-devex': HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_CHOOSE,
318
+ 'steepest':
319
+ HIGHS_SIMPLEX_EDGE_WEIGHT_STRATEGY_STEEPEST_EDGE,
320
+ None: None})
321
+
322
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
323
+
324
+ lb, ub = bounds.T.copy() # separate bounds, copy->C-cntgs
325
+ # highs_wrapper solves LHS <= A*x <= RHS, not equality constraints
326
+ with np.errstate(invalid="ignore"):
327
+ lhs_ub = -np.ones_like(b_ub)*np.inf # LHS of UB constraints is -inf
328
+ rhs_ub = b_ub # RHS of UB constraints is b_ub
329
+ lhs_eq = b_eq # Equality constraint is inequality
330
+ rhs_eq = b_eq # constraint with LHS=RHS
331
+ lhs = np.concatenate((lhs_ub, lhs_eq))
332
+ rhs = np.concatenate((rhs_ub, rhs_eq))
333
+
334
+ if issparse(A_ub) or issparse(A_eq):
335
+ A = vstack((A_ub, A_eq))
336
+ else:
337
+ A = np.vstack((A_ub, A_eq))
338
+ A = csc_matrix(A)
339
+
340
+ options = {
341
+ 'presolve': presolve,
342
+ 'sense': HIGHS_OBJECTIVE_SENSE_MINIMIZE,
343
+ 'solver': solver,
344
+ 'time_limit': time_limit,
345
+ 'highs_debug_level': MESSAGE_LEVEL_NONE,
346
+ 'dual_feasibility_tolerance': dual_feasibility_tolerance,
347
+ 'ipm_optimality_tolerance': ipm_optimality_tolerance,
348
+ 'log_to_console': disp,
349
+ 'mip_max_nodes': mip_max_nodes,
350
+ 'output_flag': disp,
351
+ 'primal_feasibility_tolerance': primal_feasibility_tolerance,
352
+ 'simplex_dual_edge_weight_strategy':
353
+ simplex_dual_edge_weight_strategy_enum,
354
+ 'simplex_strategy': HIGHS_SIMPLEX_STRATEGY_DUAL,
355
+ 'simplex_crash_strategy': HIGHS_SIMPLEX_CRASH_STRATEGY_OFF,
356
+ 'ipm_iteration_limit': maxiter,
357
+ 'simplex_iteration_limit': maxiter,
358
+ 'mip_rel_gap': mip_rel_gap,
359
+ }
360
+ options.update(unknown_options)
361
+
362
+ # np.inf doesn't work; use very large constant
363
+ rhs = _replace_inf(rhs)
364
+ lhs = _replace_inf(lhs)
365
+ lb = _replace_inf(lb)
366
+ ub = _replace_inf(ub)
367
+
368
+ if integrality is None or np.sum(integrality) == 0:
369
+ integrality = np.empty(0)
370
+ else:
371
+ integrality = np.array(integrality)
372
+
373
+ res = _highs_wrapper(c, A.indptr, A.indices, A.data, lhs, rhs,
374
+ lb, ub, integrality.astype(np.uint8), options)
375
+
376
+ # HiGHS represents constraints as lhs/rhs, so
377
+ # Ax + s = b => Ax = b - s
378
+ # and we need to split up s by A_ub and A_eq
379
+ if 'slack' in res:
380
+ slack = res['slack']
381
+ con = np.array(slack[len(b_ub):])
382
+ slack = np.array(slack[:len(b_ub)])
383
+ else:
384
+ slack, con = None, None
385
+
386
+ # lagrange multipliers for equalities/inequalities and upper/lower bounds
387
+ if 'lambda' in res:
388
+ lamda = res['lambda']
389
+ marg_ineqlin = np.array(lamda[:len(b_ub)])
390
+ marg_eqlin = np.array(lamda[len(b_ub):])
391
+ marg_upper = np.array(res['marg_bnds'][1, :])
392
+ marg_lower = np.array(res['marg_bnds'][0, :])
393
+ else:
394
+ marg_ineqlin, marg_eqlin = None, None
395
+ marg_upper, marg_lower = None, None
396
+
397
+ # this needs to be updated if we start choosing the solver intelligently
398
+
399
+ # Convert to scipy-style status and message
400
+ highs_status = res.get('status', None)
401
+ highs_message = res.get('message', None)
402
+ status, message = _highs_to_scipy_status_message(highs_status,
403
+ highs_message)
404
+
405
+ x = np.array(res['x']) if 'x' in res else None
406
+ sol = {'x': x,
407
+ 'slack': slack,
408
+ 'con': con,
409
+ 'ineqlin': OptimizeResult({
410
+ 'residual': slack,
411
+ 'marginals': marg_ineqlin,
412
+ }),
413
+ 'eqlin': OptimizeResult({
414
+ 'residual': con,
415
+ 'marginals': marg_eqlin,
416
+ }),
417
+ 'lower': OptimizeResult({
418
+ 'residual': None if x is None else x - lb,
419
+ 'marginals': marg_lower,
420
+ }),
421
+ 'upper': OptimizeResult({
422
+ 'residual': None if x is None else ub - x,
423
+ 'marginals': marg_upper
424
+ }),
425
+ 'fun': res.get('fun'),
426
+ 'status': status,
427
+ 'success': res['status'] == MODEL_STATUS_OPTIMAL,
428
+ 'message': message,
429
+ 'nit': res.get('simplex_nit', 0) or res.get('ipm_nit', 0),
430
+ 'crossover_nit': res.get('crossover_nit'),
431
+ }
432
+
433
+ if np.any(x) and integrality is not None:
434
+ sol.update({
435
+ 'mip_node_count': res.get('mip_node_count', 0),
436
+ 'mip_dual_bound': res.get('mip_dual_bound', 0.0),
437
+ 'mip_gap': res.get('mip_gap', 0.0),
438
+ })
439
+
440
+ return sol
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/bvls.cpython-310.pyc ADDED
Binary file (2.71 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/__pycache__/trf_linear.cpython-310.pyc ADDED
Binary file (5.64 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/bvls.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded-variable least-squares algorithm."""
2
+ import numpy as np
3
+ from numpy.linalg import norm, lstsq
4
+ from scipy.optimize import OptimizeResult
5
+
6
+ from .common import print_header_linear, print_iteration_linear
7
+
8
+
9
+ def compute_kkt_optimality(g, on_bound):
10
+ """Compute the maximum violation of KKT conditions."""
11
+ g_kkt = g * on_bound
12
+ free_set = on_bound == 0
13
+ g_kkt[free_set] = np.abs(g[free_set])
14
+ return np.max(g_kkt)
15
+
16
+
17
+ def bvls(A, b, x_lsq, lb, ub, tol, max_iter, verbose, rcond=None):
18
+ m, n = A.shape
19
+
20
+ x = x_lsq.copy()
21
+ on_bound = np.zeros(n)
22
+
23
+ mask = x <= lb
24
+ x[mask] = lb[mask]
25
+ on_bound[mask] = -1
26
+
27
+ mask = x >= ub
28
+ x[mask] = ub[mask]
29
+ on_bound[mask] = 1
30
+
31
+ free_set = on_bound == 0
32
+ active_set = ~free_set
33
+ free_set, = np.nonzero(free_set)
34
+
35
+ r = A.dot(x) - b
36
+ cost = 0.5 * np.dot(r, r)
37
+ initial_cost = cost
38
+ g = A.T.dot(r)
39
+
40
+ cost_change = None
41
+ step_norm = None
42
+ iteration = 0
43
+
44
+ if verbose == 2:
45
+ print_header_linear()
46
+
47
+ # This is the initialization loop. The requirement is that the
48
+ # least-squares solution on free variables is feasible before BVLS starts.
49
+ # One possible initialization is to set all variables to lower or upper
50
+ # bounds, but many iterations may be required from this state later on.
51
+ # The implemented ad-hoc procedure which intuitively should give a better
52
+ # initial state: find the least-squares solution on current free variables,
53
+ # if its feasible then stop, otherwise, set violating variables to
54
+ # corresponding bounds and continue on the reduced set of free variables.
55
+
56
+ while free_set.size > 0:
57
+ if verbose == 2:
58
+ optimality = compute_kkt_optimality(g, on_bound)
59
+ print_iteration_linear(iteration, cost, cost_change, step_norm,
60
+ optimality)
61
+
62
+ iteration += 1
63
+ x_free_old = x[free_set].copy()
64
+
65
+ A_free = A[:, free_set]
66
+ b_free = b - A.dot(x * active_set)
67
+ z = lstsq(A_free, b_free, rcond=rcond)[0]
68
+
69
+ lbv = z < lb[free_set]
70
+ ubv = z > ub[free_set]
71
+ v = lbv | ubv
72
+
73
+ if np.any(lbv):
74
+ ind = free_set[lbv]
75
+ x[ind] = lb[ind]
76
+ active_set[ind] = True
77
+ on_bound[ind] = -1
78
+
79
+ if np.any(ubv):
80
+ ind = free_set[ubv]
81
+ x[ind] = ub[ind]
82
+ active_set[ind] = True
83
+ on_bound[ind] = 1
84
+
85
+ ind = free_set[~v]
86
+ x[ind] = z[~v]
87
+
88
+ r = A.dot(x) - b
89
+ cost_new = 0.5 * np.dot(r, r)
90
+ cost_change = cost - cost_new
91
+ cost = cost_new
92
+ g = A.T.dot(r)
93
+ step_norm = norm(x[free_set] - x_free_old)
94
+
95
+ if np.any(v):
96
+ free_set = free_set[~v]
97
+ else:
98
+ break
99
+
100
+ if max_iter is None:
101
+ max_iter = n
102
+ max_iter += iteration
103
+
104
+ termination_status = None
105
+
106
+ # Main BVLS loop.
107
+
108
+ optimality = compute_kkt_optimality(g, on_bound)
109
+ for iteration in range(iteration, max_iter): # BVLS Loop A
110
+ if verbose == 2:
111
+ print_iteration_linear(iteration, cost, cost_change,
112
+ step_norm, optimality)
113
+
114
+ if optimality < tol:
115
+ termination_status = 1
116
+
117
+ if termination_status is not None:
118
+ break
119
+
120
+ move_to_free = np.argmax(g * on_bound)
121
+ on_bound[move_to_free] = 0
122
+
123
+ while True: # BVLS Loop B
124
+
125
+ free_set = on_bound == 0
126
+ active_set = ~free_set
127
+ free_set, = np.nonzero(free_set)
128
+
129
+ x_free = x[free_set]
130
+ x_free_old = x_free.copy()
131
+ lb_free = lb[free_set]
132
+ ub_free = ub[free_set]
133
+
134
+ A_free = A[:, free_set]
135
+ b_free = b - A.dot(x * active_set)
136
+ z = lstsq(A_free, b_free, rcond=rcond)[0]
137
+
138
+ lbv, = np.nonzero(z < lb_free)
139
+ ubv, = np.nonzero(z > ub_free)
140
+ v = np.hstack((lbv, ubv))
141
+
142
+ if v.size > 0:
143
+ alphas = np.hstack((
144
+ lb_free[lbv] - x_free[lbv],
145
+ ub_free[ubv] - x_free[ubv])) / (z[v] - x_free[v])
146
+
147
+ i = np.argmin(alphas)
148
+ i_free = v[i]
149
+ alpha = alphas[i]
150
+
151
+ x_free *= 1 - alpha
152
+ x_free += alpha * z
153
+ x[free_set] = x_free
154
+
155
+ if i < lbv.size:
156
+ on_bound[free_set[i_free]] = -1
157
+ else:
158
+ on_bound[free_set[i_free]] = 1
159
+ else:
160
+ x_free = z
161
+ x[free_set] = x_free
162
+ break
163
+
164
+ step_norm = norm(x_free - x_free_old)
165
+
166
+ r = A.dot(x) - b
167
+ cost_new = 0.5 * np.dot(r, r)
168
+ cost_change = cost - cost_new
169
+
170
+ if cost_change < tol * cost:
171
+ termination_status = 2
172
+ cost = cost_new
173
+
174
+ g = A.T.dot(r)
175
+ optimality = compute_kkt_optimality(g, on_bound)
176
+
177
+ if termination_status is None:
178
+ termination_status = 0
179
+
180
+ return OptimizeResult(
181
+ x=x, fun=r, cost=cost, optimality=optimality, active_mask=on_bound,
182
+ nit=iteration + 1, status=termination_status,
183
+ initial_cost=initial_cost)
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/common.py ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions used by least-squares algorithms."""
2
+ from math import copysign
3
+
4
+ import numpy as np
5
+ from numpy.linalg import norm
6
+
7
+ from scipy.linalg import cho_factor, cho_solve, LinAlgError
8
+ from scipy.sparse import issparse
9
+ from scipy.sparse.linalg import LinearOperator, aslinearoperator
10
+
11
+
12
+ EPS = np.finfo(float).eps
13
+
14
+
15
+ # Functions related to a trust-region problem.
16
+
17
+
18
+ def intersect_trust_region(x, s, Delta):
19
+ """Find the intersection of a line with the boundary of a trust region.
20
+
21
+ This function solves the quadratic equation with respect to t
22
+ ||(x + s*t)||**2 = Delta**2.
23
+
24
+ Returns
25
+ -------
26
+ t_neg, t_pos : tuple of float
27
+ Negative and positive roots.
28
+
29
+ Raises
30
+ ------
31
+ ValueError
32
+ If `s` is zero or `x` is not within the trust region.
33
+ """
34
+ a = np.dot(s, s)
35
+ if a == 0:
36
+ raise ValueError("`s` is zero.")
37
+
38
+ b = np.dot(x, s)
39
+
40
+ c = np.dot(x, x) - Delta**2
41
+ if c > 0:
42
+ raise ValueError("`x` is not within the trust region.")
43
+
44
+ d = np.sqrt(b*b - a*c) # Root from one fourth of the discriminant.
45
+
46
+ # Computations below avoid loss of significance, see "Numerical Recipes".
47
+ q = -(b + copysign(d, b))
48
+ t1 = q / a
49
+ t2 = c / q
50
+
51
+ if t1 < t2:
52
+ return t1, t2
53
+ else:
54
+ return t2, t1
55
+
56
+
57
+ def solve_lsq_trust_region(n, m, uf, s, V, Delta, initial_alpha=None,
58
+ rtol=0.01, max_iter=10):
59
+ """Solve a trust-region problem arising in least-squares minimization.
60
+
61
+ This function implements a method described by J. J. More [1]_ and used
62
+ in MINPACK, but it relies on a single SVD of Jacobian instead of series
63
+ of Cholesky decompositions. Before running this function, compute:
64
+ ``U, s, VT = svd(J, full_matrices=False)``.
65
+
66
+ Parameters
67
+ ----------
68
+ n : int
69
+ Number of variables.
70
+ m : int
71
+ Number of residuals.
72
+ uf : ndarray
73
+ Computed as U.T.dot(f).
74
+ s : ndarray
75
+ Singular values of J.
76
+ V : ndarray
77
+ Transpose of VT.
78
+ Delta : float
79
+ Radius of a trust region.
80
+ initial_alpha : float, optional
81
+ Initial guess for alpha, which might be available from a previous
82
+ iteration. If None, determined automatically.
83
+ rtol : float, optional
84
+ Stopping tolerance for the root-finding procedure. Namely, the
85
+ solution ``p`` will satisfy ``abs(norm(p) - Delta) < rtol * Delta``.
86
+ max_iter : int, optional
87
+ Maximum allowed number of iterations for the root-finding procedure.
88
+
89
+ Returns
90
+ -------
91
+ p : ndarray, shape (n,)
92
+ Found solution of a trust-region problem.
93
+ alpha : float
94
+ Positive value such that (J.T*J + alpha*I)*p = -J.T*f.
95
+ Sometimes called Levenberg-Marquardt parameter.
96
+ n_iter : int
97
+ Number of iterations made by root-finding procedure. Zero means
98
+ that Gauss-Newton step was selected as the solution.
99
+
100
+ References
101
+ ----------
102
+ .. [1] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
103
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture Notes
104
+ in Mathematics 630, Springer Verlag, pp. 105-116, 1977.
105
+ """
106
+ def phi_and_derivative(alpha, suf, s, Delta):
107
+ """Function of which to find zero.
108
+
109
+ It is defined as "norm of regularized (by alpha) least-squares
110
+ solution minus `Delta`". Refer to [1]_.
111
+ """
112
+ denom = s**2 + alpha
113
+ p_norm = norm(suf / denom)
114
+ phi = p_norm - Delta
115
+ phi_prime = -np.sum(suf ** 2 / denom**3) / p_norm
116
+ return phi, phi_prime
117
+
118
+ suf = s * uf
119
+
120
+ # Check if J has full rank and try Gauss-Newton step.
121
+ if m >= n:
122
+ threshold = EPS * m * s[0]
123
+ full_rank = s[-1] > threshold
124
+ else:
125
+ full_rank = False
126
+
127
+ if full_rank:
128
+ p = -V.dot(uf / s)
129
+ if norm(p) <= Delta:
130
+ return p, 0.0, 0
131
+
132
+ alpha_upper = norm(suf) / Delta
133
+
134
+ if full_rank:
135
+ phi, phi_prime = phi_and_derivative(0.0, suf, s, Delta)
136
+ alpha_lower = -phi / phi_prime
137
+ else:
138
+ alpha_lower = 0.0
139
+
140
+ if initial_alpha is None or not full_rank and initial_alpha == 0:
141
+ alpha = max(0.001 * alpha_upper, (alpha_lower * alpha_upper)**0.5)
142
+ else:
143
+ alpha = initial_alpha
144
+
145
+ for it in range(max_iter):
146
+ if alpha < alpha_lower or alpha > alpha_upper:
147
+ alpha = max(0.001 * alpha_upper, (alpha_lower * alpha_upper)**0.5)
148
+
149
+ phi, phi_prime = phi_and_derivative(alpha, suf, s, Delta)
150
+
151
+ if phi < 0:
152
+ alpha_upper = alpha
153
+
154
+ ratio = phi / phi_prime
155
+ alpha_lower = max(alpha_lower, alpha - ratio)
156
+ alpha -= (phi + Delta) * ratio / Delta
157
+
158
+ if np.abs(phi) < rtol * Delta:
159
+ break
160
+
161
+ p = -V.dot(suf / (s**2 + alpha))
162
+
163
+ # Make the norm of p equal to Delta, p is changed only slightly during
164
+ # this. It is done to prevent p lie outside the trust region (which can
165
+ # cause problems later).
166
+ p *= Delta / norm(p)
167
+
168
+ return p, alpha, it + 1
169
+
170
+
171
+ def solve_trust_region_2d(B, g, Delta):
172
+ """Solve a general trust-region problem in 2 dimensions.
173
+
174
+ The problem is reformulated as a 4th order algebraic equation,
175
+ the solution of which is found by numpy.roots.
176
+
177
+ Parameters
178
+ ----------
179
+ B : ndarray, shape (2, 2)
180
+ Symmetric matrix, defines a quadratic term of the function.
181
+ g : ndarray, shape (2,)
182
+ Defines a linear term of the function.
183
+ Delta : float
184
+ Radius of a trust region.
185
+
186
+ Returns
187
+ -------
188
+ p : ndarray, shape (2,)
189
+ Found solution.
190
+ newton_step : bool
191
+ Whether the returned solution is the Newton step which lies within
192
+ the trust region.
193
+ """
194
+ try:
195
+ R, lower = cho_factor(B)
196
+ p = -cho_solve((R, lower), g)
197
+ if np.dot(p, p) <= Delta**2:
198
+ return p, True
199
+ except LinAlgError:
200
+ pass
201
+
202
+ a = B[0, 0] * Delta**2
203
+ b = B[0, 1] * Delta**2
204
+ c = B[1, 1] * Delta**2
205
+
206
+ d = g[0] * Delta
207
+ f = g[1] * Delta
208
+
209
+ coeffs = np.array(
210
+ [-b + d, 2 * (a - c + f), 6 * b, 2 * (-a + c + f), -b - d])
211
+ t = np.roots(coeffs) # Can handle leading zeros.
212
+ t = np.real(t[np.isreal(t)])
213
+
214
+ p = Delta * np.vstack((2 * t / (1 + t**2), (1 - t**2) / (1 + t**2)))
215
+ value = 0.5 * np.sum(p * B.dot(p), axis=0) + np.dot(g, p)
216
+ i = np.argmin(value)
217
+ p = p[:, i]
218
+
219
+ return p, False
220
+
221
+
222
+ def update_tr_radius(Delta, actual_reduction, predicted_reduction,
223
+ step_norm, bound_hit):
224
+ """Update the radius of a trust region based on the cost reduction.
225
+
226
+ Returns
227
+ -------
228
+ Delta : float
229
+ New radius.
230
+ ratio : float
231
+ Ratio between actual and predicted reductions.
232
+ """
233
+ if predicted_reduction > 0:
234
+ ratio = actual_reduction / predicted_reduction
235
+ elif predicted_reduction == actual_reduction == 0:
236
+ ratio = 1
237
+ else:
238
+ ratio = 0
239
+
240
+ if ratio < 0.25:
241
+ Delta = 0.25 * step_norm
242
+ elif ratio > 0.75 and bound_hit:
243
+ Delta *= 2.0
244
+
245
+ return Delta, ratio
246
+
247
+
248
+ # Construction and minimization of quadratic functions.
249
+
250
+
251
+ def build_quadratic_1d(J, g, s, diag=None, s0=None):
252
+ """Parameterize a multivariate quadratic function along a line.
253
+
254
+ The resulting univariate quadratic function is given as follows::
255
+
256
+ f(t) = 0.5 * (s0 + s*t).T * (J.T*J + diag) * (s0 + s*t) +
257
+ g.T * (s0 + s*t)
258
+
259
+ Parameters
260
+ ----------
261
+ J : ndarray, sparse matrix or LinearOperator shape (m, n)
262
+ Jacobian matrix, affects the quadratic term.
263
+ g : ndarray, shape (n,)
264
+ Gradient, defines the linear term.
265
+ s : ndarray, shape (n,)
266
+ Direction vector of a line.
267
+ diag : None or ndarray with shape (n,), optional
268
+ Addition diagonal part, affects the quadratic term.
269
+ If None, assumed to be 0.
270
+ s0 : None or ndarray with shape (n,), optional
271
+ Initial point. If None, assumed to be 0.
272
+
273
+ Returns
274
+ -------
275
+ a : float
276
+ Coefficient for t**2.
277
+ b : float
278
+ Coefficient for t.
279
+ c : float
280
+ Free term. Returned only if `s0` is provided.
281
+ """
282
+ v = J.dot(s)
283
+ a = np.dot(v, v)
284
+ if diag is not None:
285
+ a += np.dot(s * diag, s)
286
+ a *= 0.5
287
+
288
+ b = np.dot(g, s)
289
+
290
+ if s0 is not None:
291
+ u = J.dot(s0)
292
+ b += np.dot(u, v)
293
+ c = 0.5 * np.dot(u, u) + np.dot(g, s0)
294
+ if diag is not None:
295
+ b += np.dot(s0 * diag, s)
296
+ c += 0.5 * np.dot(s0 * diag, s0)
297
+ return a, b, c
298
+ else:
299
+ return a, b
300
+
301
+
302
+ def minimize_quadratic_1d(a, b, lb, ub, c=0):
303
+ """Minimize a 1-D quadratic function subject to bounds.
304
+
305
+ The free term `c` is 0 by default. Bounds must be finite.
306
+
307
+ Returns
308
+ -------
309
+ t : float
310
+ Minimum point.
311
+ y : float
312
+ Minimum value.
313
+ """
314
+ t = [lb, ub]
315
+ if a != 0:
316
+ extremum = -0.5 * b / a
317
+ if lb < extremum < ub:
318
+ t.append(extremum)
319
+ t = np.asarray(t)
320
+ y = t * (a * t + b) + c
321
+ min_index = np.argmin(y)
322
+ return t[min_index], y[min_index]
323
+
324
+
325
+ def evaluate_quadratic(J, g, s, diag=None):
326
+ """Compute values of a quadratic function arising in least squares.
327
+
328
+ The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s.
329
+
330
+ Parameters
331
+ ----------
332
+ J : ndarray, sparse matrix or LinearOperator, shape (m, n)
333
+ Jacobian matrix, affects the quadratic term.
334
+ g : ndarray, shape (n,)
335
+ Gradient, defines the linear term.
336
+ s : ndarray, shape (k, n) or (n,)
337
+ Array containing steps as rows.
338
+ diag : ndarray, shape (n,), optional
339
+ Addition diagonal part, affects the quadratic term.
340
+ If None, assumed to be 0.
341
+
342
+ Returns
343
+ -------
344
+ values : ndarray with shape (k,) or float
345
+ Values of the function. If `s` was 2-D, then ndarray is
346
+ returned, otherwise, float is returned.
347
+ """
348
+ if s.ndim == 1:
349
+ Js = J.dot(s)
350
+ q = np.dot(Js, Js)
351
+ if diag is not None:
352
+ q += np.dot(s * diag, s)
353
+ else:
354
+ Js = J.dot(s.T)
355
+ q = np.sum(Js**2, axis=0)
356
+ if diag is not None:
357
+ q += np.sum(diag * s**2, axis=1)
358
+
359
+ l = np.dot(s, g)
360
+
361
+ return 0.5 * q + l
362
+
363
+
364
+ # Utility functions to work with bound constraints.
365
+
366
+
367
+ def in_bounds(x, lb, ub):
368
+ """Check if a point lies within bounds."""
369
+ return np.all((x >= lb) & (x <= ub))
370
+
371
+
372
+ def step_size_to_bound(x, s, lb, ub):
373
+ """Compute a min_step size required to reach a bound.
374
+
375
+ The function computes a positive scalar t, such that x + s * t is on
376
+ the bound.
377
+
378
+ Returns
379
+ -------
380
+ step : float
381
+ Computed step. Non-negative value.
382
+ hits : ndarray of int with shape of x
383
+ Each element indicates whether a corresponding variable reaches the
384
+ bound:
385
+
386
+ * 0 - the bound was not hit.
387
+ * -1 - the lower bound was hit.
388
+ * 1 - the upper bound was hit.
389
+ """
390
+ non_zero = np.nonzero(s)
391
+ s_non_zero = s[non_zero]
392
+ steps = np.empty_like(x)
393
+ steps.fill(np.inf)
394
+ with np.errstate(over='ignore'):
395
+ steps[non_zero] = np.maximum((lb - x)[non_zero] / s_non_zero,
396
+ (ub - x)[non_zero] / s_non_zero)
397
+ min_step = np.min(steps)
398
+ return min_step, np.equal(steps, min_step) * np.sign(s).astype(int)
399
+
400
+
401
+ def find_active_constraints(x, lb, ub, rtol=1e-10):
402
+ """Determine which constraints are active in a given point.
403
+
404
+ The threshold is computed using `rtol` and the absolute value of the
405
+ closest bound.
406
+
407
+ Returns
408
+ -------
409
+ active : ndarray of int with shape of x
410
+ Each component shows whether the corresponding constraint is active:
411
+
412
+ * 0 - a constraint is not active.
413
+ * -1 - a lower bound is active.
414
+ * 1 - a upper bound is active.
415
+ """
416
+ active = np.zeros_like(x, dtype=int)
417
+
418
+ if rtol == 0:
419
+ active[x <= lb] = -1
420
+ active[x >= ub] = 1
421
+ return active
422
+
423
+ lower_dist = x - lb
424
+ upper_dist = ub - x
425
+
426
+ lower_threshold = rtol * np.maximum(1, np.abs(lb))
427
+ upper_threshold = rtol * np.maximum(1, np.abs(ub))
428
+
429
+ lower_active = (np.isfinite(lb) &
430
+ (lower_dist <= np.minimum(upper_dist, lower_threshold)))
431
+ active[lower_active] = -1
432
+
433
+ upper_active = (np.isfinite(ub) &
434
+ (upper_dist <= np.minimum(lower_dist, upper_threshold)))
435
+ active[upper_active] = 1
436
+
437
+ return active
438
+
439
+
440
+ def make_strictly_feasible(x, lb, ub, rstep=1e-10):
441
+ """Shift a point to the interior of a feasible region.
442
+
443
+ Each element of the returned vector is at least at a relative distance
444
+ `rstep` from the closest bound. If ``rstep=0`` then `np.nextafter` is used.
445
+ """
446
+ x_new = x.copy()
447
+
448
+ active = find_active_constraints(x, lb, ub, rstep)
449
+ lower_mask = np.equal(active, -1)
450
+ upper_mask = np.equal(active, 1)
451
+
452
+ if rstep == 0:
453
+ x_new[lower_mask] = np.nextafter(lb[lower_mask], ub[lower_mask])
454
+ x_new[upper_mask] = np.nextafter(ub[upper_mask], lb[upper_mask])
455
+ else:
456
+ x_new[lower_mask] = (lb[lower_mask] +
457
+ rstep * np.maximum(1, np.abs(lb[lower_mask])))
458
+ x_new[upper_mask] = (ub[upper_mask] -
459
+ rstep * np.maximum(1, np.abs(ub[upper_mask])))
460
+
461
+ tight_bounds = (x_new < lb) | (x_new > ub)
462
+ x_new[tight_bounds] = 0.5 * (lb[tight_bounds] + ub[tight_bounds])
463
+
464
+ return x_new
465
+
466
+
467
+ def CL_scaling_vector(x, g, lb, ub):
468
+ """Compute Coleman-Li scaling vector and its derivatives.
469
+
470
+ Components of a vector v are defined as follows::
471
+
472
+ | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf
473
+ v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf
474
+ | 1, otherwise
475
+
476
+ According to this definition v[i] >= 0 for all i. It differs from the
477
+ definition in paper [1]_ (eq. (2.2)), where the absolute value of v is
478
+ used. Both definitions are equivalent down the line.
479
+ Derivatives of v with respect to x take value 1, -1 or 0 depending on a
480
+ case.
481
+
482
+ Returns
483
+ -------
484
+ v : ndarray with shape of x
485
+ Scaling vector.
486
+ dv : ndarray with shape of x
487
+ Derivatives of v[i] with respect to x[i], diagonal elements of v's
488
+ Jacobian.
489
+
490
+ References
491
+ ----------
492
+ .. [1] M.A. Branch, T.F. Coleman, and Y. Li, "A Subspace, Interior,
493
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
494
+ Minimization Problems," SIAM Journal on Scientific Computing,
495
+ Vol. 21, Number 1, pp 1-23, 1999.
496
+ """
497
+ v = np.ones_like(x)
498
+ dv = np.zeros_like(x)
499
+
500
+ mask = (g < 0) & np.isfinite(ub)
501
+ v[mask] = ub[mask] - x[mask]
502
+ dv[mask] = -1
503
+
504
+ mask = (g > 0) & np.isfinite(lb)
505
+ v[mask] = x[mask] - lb[mask]
506
+ dv[mask] = 1
507
+
508
+ return v, dv
509
+
510
+
511
+ def reflective_transformation(y, lb, ub):
512
+ """Compute reflective transformation and its gradient."""
513
+ if in_bounds(y, lb, ub):
514
+ return y, np.ones_like(y)
515
+
516
+ lb_finite = np.isfinite(lb)
517
+ ub_finite = np.isfinite(ub)
518
+
519
+ x = y.copy()
520
+ g_negative = np.zeros_like(y, dtype=bool)
521
+
522
+ mask = lb_finite & ~ub_finite
523
+ x[mask] = np.maximum(y[mask], 2 * lb[mask] - y[mask])
524
+ g_negative[mask] = y[mask] < lb[mask]
525
+
526
+ mask = ~lb_finite & ub_finite
527
+ x[mask] = np.minimum(y[mask], 2 * ub[mask] - y[mask])
528
+ g_negative[mask] = y[mask] > ub[mask]
529
+
530
+ mask = lb_finite & ub_finite
531
+ d = ub - lb
532
+ t = np.remainder(y[mask] - lb[mask], 2 * d[mask])
533
+ x[mask] = lb[mask] + np.minimum(t, 2 * d[mask] - t)
534
+ g_negative[mask] = t > d[mask]
535
+
536
+ g = np.ones_like(y)
537
+ g[g_negative] = -1
538
+
539
+ return x, g
540
+
541
+
542
+ # Functions to display algorithm's progress.
543
+
544
+
545
+ def print_header_nonlinear():
546
+ print("{:^15}{:^15}{:^15}{:^15}{:^15}{:^15}"
547
+ .format("Iteration", "Total nfev", "Cost", "Cost reduction",
548
+ "Step norm", "Optimality"))
549
+
550
+
551
+ def print_iteration_nonlinear(iteration, nfev, cost, cost_reduction,
552
+ step_norm, optimality):
553
+ if cost_reduction is None:
554
+ cost_reduction = " " * 15
555
+ else:
556
+ cost_reduction = f"{cost_reduction:^15.2e}"
557
+
558
+ if step_norm is None:
559
+ step_norm = " " * 15
560
+ else:
561
+ step_norm = f"{step_norm:^15.2e}"
562
+
563
+ print("{:^15}{:^15}{:^15.4e}{}{}{:^15.2e}"
564
+ .format(iteration, nfev, cost, cost_reduction,
565
+ step_norm, optimality))
566
+
567
+
568
+ def print_header_linear():
569
+ print("{:^15}{:^15}{:^15}{:^15}{:^15}"
570
+ .format("Iteration", "Cost", "Cost reduction", "Step norm",
571
+ "Optimality"))
572
+
573
+
574
+ def print_iteration_linear(iteration, cost, cost_reduction, step_norm,
575
+ optimality):
576
+ if cost_reduction is None:
577
+ cost_reduction = " " * 15
578
+ else:
579
+ cost_reduction = f"{cost_reduction:^15.2e}"
580
+
581
+ if step_norm is None:
582
+ step_norm = " " * 15
583
+ else:
584
+ step_norm = f"{step_norm:^15.2e}"
585
+
586
+ print(f"{iteration:^15}{cost:^15.4e}{cost_reduction}{step_norm}{optimality:^15.2e}")
587
+
588
+
589
+ # Simple helper functions.
590
+
591
+
592
+ def compute_grad(J, f):
593
+ """Compute gradient of the least-squares cost function."""
594
+ if isinstance(J, LinearOperator):
595
+ return J.rmatvec(f)
596
+ else:
597
+ return J.T.dot(f)
598
+
599
+
600
+ def compute_jac_scale(J, scale_inv_old=None):
601
+ """Compute variables scale based on the Jacobian matrix."""
602
+ if issparse(J):
603
+ scale_inv = np.asarray(J.power(2).sum(axis=0)).ravel()**0.5
604
+ else:
605
+ scale_inv = np.sum(J**2, axis=0)**0.5
606
+
607
+ if scale_inv_old is None:
608
+ scale_inv[scale_inv == 0] = 1
609
+ else:
610
+ scale_inv = np.maximum(scale_inv, scale_inv_old)
611
+
612
+ return 1 / scale_inv, scale_inv
613
+
614
+
615
+ def left_multiplied_operator(J, d):
616
+ """Return diag(d) J as LinearOperator."""
617
+ J = aslinearoperator(J)
618
+
619
+ def matvec(x):
620
+ return d * J.matvec(x)
621
+
622
+ def matmat(X):
623
+ return d[:, np.newaxis] * J.matmat(X)
624
+
625
+ def rmatvec(x):
626
+ return J.rmatvec(x.ravel() * d)
627
+
628
+ return LinearOperator(J.shape, matvec=matvec, matmat=matmat,
629
+ rmatvec=rmatvec)
630
+
631
+
632
+ def right_multiplied_operator(J, d):
633
+ """Return J diag(d) as LinearOperator."""
634
+ J = aslinearoperator(J)
635
+
636
+ def matvec(x):
637
+ return J.matvec(np.ravel(x) * d)
638
+
639
+ def matmat(X):
640
+ return J.matmat(X * d[:, np.newaxis])
641
+
642
+ def rmatvec(x):
643
+ return d * J.rmatvec(x)
644
+
645
+ return LinearOperator(J.shape, matvec=matvec, matmat=matmat,
646
+ rmatvec=rmatvec)
647
+
648
+
649
+ def regularized_lsq_operator(J, diag):
650
+ """Return a matrix arising in regularized least squares as LinearOperator.
651
+
652
+ The matrix is
653
+ [ J ]
654
+ [ D ]
655
+ where D is diagonal matrix with elements from `diag`.
656
+ """
657
+ J = aslinearoperator(J)
658
+ m, n = J.shape
659
+
660
+ def matvec(x):
661
+ return np.hstack((J.matvec(x), diag * x))
662
+
663
+ def rmatvec(x):
664
+ x1 = x[:m]
665
+ x2 = x[m:]
666
+ return J.rmatvec(x1) + diag * x2
667
+
668
+ return LinearOperator((m + n, n), matvec=matvec, rmatvec=rmatvec)
669
+
670
+
671
+ def right_multiply(J, d, copy=True):
672
+ """Compute J diag(d).
673
+
674
+ If `copy` is False, `J` is modified in place (unless being LinearOperator).
675
+ """
676
+ if copy and not isinstance(J, LinearOperator):
677
+ J = J.copy()
678
+
679
+ if issparse(J):
680
+ J.data *= d.take(J.indices, mode='clip') # scikit-learn recipe.
681
+ elif isinstance(J, LinearOperator):
682
+ J = right_multiplied_operator(J, d)
683
+ else:
684
+ J *= d
685
+
686
+ return J
687
+
688
+
689
+ def left_multiply(J, d, copy=True):
690
+ """Compute diag(d) J.
691
+
692
+ If `copy` is False, `J` is modified in place (unless being LinearOperator).
693
+ """
694
+ if copy and not isinstance(J, LinearOperator):
695
+ J = J.copy()
696
+
697
+ if issparse(J):
698
+ J.data *= np.repeat(d, np.diff(J.indptr)) # scikit-learn recipe.
699
+ elif isinstance(J, LinearOperator):
700
+ J = left_multiplied_operator(J, d)
701
+ else:
702
+ J *= d[:, np.newaxis]
703
+
704
+ return J
705
+
706
+
707
+ def check_termination(dF, F, dx_norm, x_norm, ratio, ftol, xtol):
708
+ """Check termination condition for nonlinear least squares."""
709
+ ftol_satisfied = dF < ftol * F and ratio > 0.25
710
+ xtol_satisfied = dx_norm < xtol * (xtol + x_norm)
711
+
712
+ if ftol_satisfied and xtol_satisfied:
713
+ return 4
714
+ elif ftol_satisfied:
715
+ return 2
716
+ elif xtol_satisfied:
717
+ return 3
718
+ else:
719
+ return None
720
+
721
+
722
+ def scale_for_robust_loss_function(J, f, rho):
723
+ """Scale Jacobian and residuals for a robust loss function.
724
+
725
+ Arrays are modified in place.
726
+ """
727
+ J_scale = rho[1] + 2 * rho[2] * f**2
728
+ J_scale[J_scale < EPS] = EPS
729
+ J_scale **= 0.5
730
+
731
+ f *= rho[1] / J_scale
732
+
733
+ return left_multiply(J, J_scale, copy=False), f
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/dogbox.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dogleg algorithm with rectangular trust regions for least-squares minimization.
3
+
4
+ The description of the algorithm can be found in [Voglis]_. The algorithm does
5
+ trust-region iterations, but the shape of trust regions is rectangular as
6
+ opposed to conventional elliptical. The intersection of a trust region and
7
+ an initial feasible region is again some rectangle. Thus, on each iteration a
8
+ bound-constrained quadratic optimization problem is solved.
9
+
10
+ A quadratic problem is solved by well-known dogleg approach, where the
11
+ function is minimized along piecewise-linear "dogleg" path [NumOpt]_,
12
+ Chapter 4. If Jacobian is not rank-deficient then the function is decreasing
13
+ along this path, and optimization amounts to simply following along this
14
+ path as long as a point stays within the bounds. A constrained Cauchy step
15
+ (along the anti-gradient) is considered for safety in rank deficient cases,
16
+ in this situations the convergence might be slow.
17
+
18
+ If during iterations some variable hit the initial bound and the component
19
+ of anti-gradient points outside the feasible region, then a next dogleg step
20
+ won't make any progress. At this state such variables satisfy first-order
21
+ optimality conditions and they are excluded before computing a next dogleg
22
+ step.
23
+
24
+ Gauss-Newton step can be computed exactly by `numpy.linalg.lstsq` (for dense
25
+ Jacobian matrices) or by iterative procedure `scipy.sparse.linalg.lsmr` (for
26
+ dense and sparse matrices, or Jacobian being LinearOperator). The second
27
+ option allows to solve very large problems (up to couple of millions of
28
+ residuals on a regular PC), provided the Jacobian matrix is sufficiently
29
+ sparse. But note that dogbox is not very good for solving problems with
30
+ large number of constraints, because of variables exclusion-inclusion on each
31
+ iteration (a required number of function evaluations might be high or accuracy
32
+ of a solution will be poor), thus its large-scale usage is probably limited
33
+ to unconstrained problems.
34
+
35
+ References
36
+ ----------
37
+ .. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region Dogleg
38
+ Approach for Unconstrained and Bound Constrained Nonlinear
39
+ Optimization", WSEAS International Conference on Applied
40
+ Mathematics, Corfu, Greece, 2004.
41
+ .. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization, 2nd edition".
42
+ """
43
+ import numpy as np
44
+ from numpy.linalg import lstsq, norm
45
+
46
+ from scipy.sparse.linalg import LinearOperator, aslinearoperator, lsmr
47
+ from scipy.optimize import OptimizeResult
48
+
49
+ from .common import (
50
+ step_size_to_bound, in_bounds, update_tr_radius, evaluate_quadratic,
51
+ build_quadratic_1d, minimize_quadratic_1d, compute_grad,
52
+ compute_jac_scale, check_termination, scale_for_robust_loss_function,
53
+ print_header_nonlinear, print_iteration_nonlinear)
54
+
55
+
56
+ def lsmr_operator(Jop, d, active_set):
57
+ """Compute LinearOperator to use in LSMR by dogbox algorithm.
58
+
59
+ `active_set` mask is used to excluded active variables from computations
60
+ of matrix-vector products.
61
+ """
62
+ m, n = Jop.shape
63
+
64
+ def matvec(x):
65
+ x_free = x.ravel().copy()
66
+ x_free[active_set] = 0
67
+ return Jop.matvec(x * d)
68
+
69
+ def rmatvec(x):
70
+ r = d * Jop.rmatvec(x)
71
+ r[active_set] = 0
72
+ return r
73
+
74
+ return LinearOperator((m, n), matvec=matvec, rmatvec=rmatvec, dtype=float)
75
+
76
+
77
+ def find_intersection(x, tr_bounds, lb, ub):
78
+ """Find intersection of trust-region bounds and initial bounds.
79
+
80
+ Returns
81
+ -------
82
+ lb_total, ub_total : ndarray with shape of x
83
+ Lower and upper bounds of the intersection region.
84
+ orig_l, orig_u : ndarray of bool with shape of x
85
+ True means that an original bound is taken as a corresponding bound
86
+ in the intersection region.
87
+ tr_l, tr_u : ndarray of bool with shape of x
88
+ True means that a trust-region bound is taken as a corresponding bound
89
+ in the intersection region.
90
+ """
91
+ lb_centered = lb - x
92
+ ub_centered = ub - x
93
+
94
+ lb_total = np.maximum(lb_centered, -tr_bounds)
95
+ ub_total = np.minimum(ub_centered, tr_bounds)
96
+
97
+ orig_l = np.equal(lb_total, lb_centered)
98
+ orig_u = np.equal(ub_total, ub_centered)
99
+
100
+ tr_l = np.equal(lb_total, -tr_bounds)
101
+ tr_u = np.equal(ub_total, tr_bounds)
102
+
103
+ return lb_total, ub_total, orig_l, orig_u, tr_l, tr_u
104
+
105
+
106
+ def dogleg_step(x, newton_step, g, a, b, tr_bounds, lb, ub):
107
+ """Find dogleg step in a rectangular region.
108
+
109
+ Returns
110
+ -------
111
+ step : ndarray, shape (n,)
112
+ Computed dogleg step.
113
+ bound_hits : ndarray of int, shape (n,)
114
+ Each component shows whether a corresponding variable hits the
115
+ initial bound after the step is taken:
116
+ * 0 - a variable doesn't hit the bound.
117
+ * -1 - lower bound is hit.
118
+ * 1 - upper bound is hit.
119
+ tr_hit : bool
120
+ Whether the step hit the boundary of the trust-region.
121
+ """
122
+ lb_total, ub_total, orig_l, orig_u, tr_l, tr_u = find_intersection(
123
+ x, tr_bounds, lb, ub
124
+ )
125
+ bound_hits = np.zeros_like(x, dtype=int)
126
+
127
+ if in_bounds(newton_step, lb_total, ub_total):
128
+ return newton_step, bound_hits, False
129
+
130
+ to_bounds, _ = step_size_to_bound(np.zeros_like(x), -g, lb_total, ub_total)
131
+
132
+ # The classical dogleg algorithm would check if Cauchy step fits into
133
+ # the bounds, and just return it constrained version if not. But in a
134
+ # rectangular trust region it makes sense to try to improve constrained
135
+ # Cauchy step too. Thus, we don't distinguish these two cases.
136
+
137
+ cauchy_step = -minimize_quadratic_1d(a, b, 0, to_bounds)[0] * g
138
+
139
+ step_diff = newton_step - cauchy_step
140
+ step_size, hits = step_size_to_bound(cauchy_step, step_diff,
141
+ lb_total, ub_total)
142
+ bound_hits[(hits < 0) & orig_l] = -1
143
+ bound_hits[(hits > 0) & orig_u] = 1
144
+ tr_hit = np.any((hits < 0) & tr_l | (hits > 0) & tr_u)
145
+
146
+ return cauchy_step + step_size * step_diff, bound_hits, tr_hit
147
+
148
+
149
+ def dogbox(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
150
+ loss_function, tr_solver, tr_options, verbose):
151
+ f = f0
152
+ f_true = f.copy()
153
+ nfev = 1
154
+
155
+ J = J0
156
+ njev = 1
157
+
158
+ if loss_function is not None:
159
+ rho = loss_function(f)
160
+ cost = 0.5 * np.sum(rho[0])
161
+ J, f = scale_for_robust_loss_function(J, f, rho)
162
+ else:
163
+ cost = 0.5 * np.dot(f, f)
164
+
165
+ g = compute_grad(J, f)
166
+
167
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
168
+ if jac_scale:
169
+ scale, scale_inv = compute_jac_scale(J)
170
+ else:
171
+ scale, scale_inv = x_scale, 1 / x_scale
172
+
173
+ Delta = norm(x0 * scale_inv, ord=np.inf)
174
+ if Delta == 0:
175
+ Delta = 1.0
176
+
177
+ on_bound = np.zeros_like(x0, dtype=int)
178
+ on_bound[np.equal(x0, lb)] = -1
179
+ on_bound[np.equal(x0, ub)] = 1
180
+
181
+ x = x0
182
+ step = np.empty_like(x0)
183
+
184
+ if max_nfev is None:
185
+ max_nfev = x0.size * 100
186
+
187
+ termination_status = None
188
+ iteration = 0
189
+ step_norm = None
190
+ actual_reduction = None
191
+
192
+ if verbose == 2:
193
+ print_header_nonlinear()
194
+
195
+ while True:
196
+ active_set = on_bound * g < 0
197
+ free_set = ~active_set
198
+
199
+ g_free = g[free_set]
200
+ g_full = g.copy()
201
+ g[active_set] = 0
202
+
203
+ g_norm = norm(g, ord=np.inf)
204
+ if g_norm < gtol:
205
+ termination_status = 1
206
+
207
+ if verbose == 2:
208
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
209
+ step_norm, g_norm)
210
+
211
+ if termination_status is not None or nfev == max_nfev:
212
+ break
213
+
214
+ x_free = x[free_set]
215
+ lb_free = lb[free_set]
216
+ ub_free = ub[free_set]
217
+ scale_free = scale[free_set]
218
+
219
+ # Compute (Gauss-)Newton and build quadratic model for Cauchy step.
220
+ if tr_solver == 'exact':
221
+ J_free = J[:, free_set]
222
+ newton_step = lstsq(J_free, -f, rcond=-1)[0]
223
+
224
+ # Coefficients for the quadratic model along the anti-gradient.
225
+ a, b = build_quadratic_1d(J_free, g_free, -g_free)
226
+ elif tr_solver == 'lsmr':
227
+ Jop = aslinearoperator(J)
228
+
229
+ # We compute lsmr step in scaled variables and then
230
+ # transform back to normal variables, if lsmr would give exact lsq
231
+ # solution, this would be equivalent to not doing any
232
+ # transformations, but from experience it's better this way.
233
+
234
+ # We pass active_set to make computations as if we selected
235
+ # the free subset of J columns, but without actually doing any
236
+ # slicing, which is expensive for sparse matrices and impossible
237
+ # for LinearOperator.
238
+
239
+ lsmr_op = lsmr_operator(Jop, scale, active_set)
240
+ newton_step = -lsmr(lsmr_op, f, **tr_options)[0][free_set]
241
+ newton_step *= scale_free
242
+
243
+ # Components of g for active variables were zeroed, so this call
244
+ # is correct and equivalent to using J_free and g_free.
245
+ a, b = build_quadratic_1d(Jop, g, -g)
246
+
247
+ actual_reduction = -1.0
248
+ while actual_reduction <= 0 and nfev < max_nfev:
249
+ tr_bounds = Delta * scale_free
250
+
251
+ step_free, on_bound_free, tr_hit = dogleg_step(
252
+ x_free, newton_step, g_free, a, b, tr_bounds, lb_free, ub_free)
253
+
254
+ step.fill(0.0)
255
+ step[free_set] = step_free
256
+
257
+ if tr_solver == 'exact':
258
+ predicted_reduction = -evaluate_quadratic(J_free, g_free,
259
+ step_free)
260
+ elif tr_solver == 'lsmr':
261
+ predicted_reduction = -evaluate_quadratic(Jop, g, step)
262
+
263
+ # gh11403 ensure that solution is fully within bounds.
264
+ x_new = np.clip(x + step, lb, ub)
265
+
266
+ f_new = fun(x_new)
267
+ nfev += 1
268
+
269
+ step_h_norm = norm(step * scale_inv, ord=np.inf)
270
+
271
+ if not np.all(np.isfinite(f_new)):
272
+ Delta = 0.25 * step_h_norm
273
+ continue
274
+
275
+ # Usual trust-region step quality estimation.
276
+ if loss_function is not None:
277
+ cost_new = loss_function(f_new, cost_only=True)
278
+ else:
279
+ cost_new = 0.5 * np.dot(f_new, f_new)
280
+ actual_reduction = cost - cost_new
281
+
282
+ Delta, ratio = update_tr_radius(
283
+ Delta, actual_reduction, predicted_reduction,
284
+ step_h_norm, tr_hit
285
+ )
286
+
287
+ step_norm = norm(step)
288
+ termination_status = check_termination(
289
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
290
+
291
+ if termination_status is not None:
292
+ break
293
+
294
+ if actual_reduction > 0:
295
+ on_bound[free_set] = on_bound_free
296
+
297
+ x = x_new
298
+ # Set variables exactly at the boundary.
299
+ mask = on_bound == -1
300
+ x[mask] = lb[mask]
301
+ mask = on_bound == 1
302
+ x[mask] = ub[mask]
303
+
304
+ f = f_new
305
+ f_true = f.copy()
306
+
307
+ cost = cost_new
308
+
309
+ J = jac(x, f)
310
+ njev += 1
311
+
312
+ if loss_function is not None:
313
+ rho = loss_function(f)
314
+ J, f = scale_for_robust_loss_function(J, f, rho)
315
+
316
+ g = compute_grad(J, f)
317
+
318
+ if jac_scale:
319
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
320
+ else:
321
+ step_norm = 0
322
+ actual_reduction = 0
323
+
324
+ iteration += 1
325
+
326
+ if termination_status is None:
327
+ termination_status = 0
328
+
329
+ return OptimizeResult(
330
+ x=x, cost=cost, fun=f_true, jac=J, grad=g_full, optimality=g_norm,
331
+ active_mask=on_bound, nfev=nfev, njev=njev, status=termination_status)
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/least_squares.py ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generic interface for least-squares minimization."""
2
+ from warnings import warn
3
+
4
+ import numpy as np
5
+ from numpy.linalg import norm
6
+
7
+ from scipy.sparse import issparse
8
+ from scipy.sparse.linalg import LinearOperator
9
+ from scipy.optimize import _minpack, OptimizeResult
10
+ from scipy.optimize._numdiff import approx_derivative, group_columns
11
+ from scipy.optimize._minimize import Bounds
12
+
13
+ from .trf import trf
14
+ from .dogbox import dogbox
15
+ from .common import EPS, in_bounds, make_strictly_feasible
16
+
17
+
18
+ TERMINATION_MESSAGES = {
19
+ -1: "Improper input parameters status returned from `leastsq`",
20
+ 0: "The maximum number of function evaluations is exceeded.",
21
+ 1: "`gtol` termination condition is satisfied.",
22
+ 2: "`ftol` termination condition is satisfied.",
23
+ 3: "`xtol` termination condition is satisfied.",
24
+ 4: "Both `ftol` and `xtol` termination conditions are satisfied."
25
+ }
26
+
27
+
28
+ FROM_MINPACK_TO_COMMON = {
29
+ 0: -1, # Improper input parameters from MINPACK.
30
+ 1: 2,
31
+ 2: 3,
32
+ 3: 4,
33
+ 4: 1,
34
+ 5: 0
35
+ # There are 6, 7, 8 for too small tolerance parameters,
36
+ # but we guard against it by checking ftol, xtol, gtol beforehand.
37
+ }
38
+
39
+
40
+ def call_minpack(fun, x0, jac, ftol, xtol, gtol, max_nfev, x_scale, diff_step):
41
+ n = x0.size
42
+
43
+ if diff_step is None:
44
+ epsfcn = EPS
45
+ else:
46
+ epsfcn = diff_step**2
47
+
48
+ # Compute MINPACK's `diag`, which is inverse of our `x_scale` and
49
+ # ``x_scale='jac'`` corresponds to ``diag=None``.
50
+ if isinstance(x_scale, str) and x_scale == 'jac':
51
+ diag = None
52
+ else:
53
+ diag = 1 / x_scale
54
+
55
+ full_output = True
56
+ col_deriv = False
57
+ factor = 100.0
58
+
59
+ if jac is None:
60
+ if max_nfev is None:
61
+ # n squared to account for Jacobian evaluations.
62
+ max_nfev = 100 * n * (n + 1)
63
+ x, info, status = _minpack._lmdif(
64
+ fun, x0, (), full_output, ftol, xtol, gtol,
65
+ max_nfev, epsfcn, factor, diag)
66
+ else:
67
+ if max_nfev is None:
68
+ max_nfev = 100 * n
69
+ x, info, status = _minpack._lmder(
70
+ fun, jac, x0, (), full_output, col_deriv,
71
+ ftol, xtol, gtol, max_nfev, factor, diag)
72
+
73
+ f = info['fvec']
74
+
75
+ if callable(jac):
76
+ J = jac(x)
77
+ else:
78
+ J = np.atleast_2d(approx_derivative(fun, x))
79
+
80
+ cost = 0.5 * np.dot(f, f)
81
+ g = J.T.dot(f)
82
+ g_norm = norm(g, ord=np.inf)
83
+
84
+ nfev = info['nfev']
85
+ njev = info.get('njev', None)
86
+
87
+ status = FROM_MINPACK_TO_COMMON[status]
88
+ active_mask = np.zeros_like(x0, dtype=int)
89
+
90
+ return OptimizeResult(
91
+ x=x, cost=cost, fun=f, jac=J, grad=g, optimality=g_norm,
92
+ active_mask=active_mask, nfev=nfev, njev=njev, status=status)
93
+
94
+
95
+ def prepare_bounds(bounds, n):
96
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
97
+ if lb.ndim == 0:
98
+ lb = np.resize(lb, n)
99
+
100
+ if ub.ndim == 0:
101
+ ub = np.resize(ub, n)
102
+
103
+ return lb, ub
104
+
105
+
106
+ def check_tolerance(ftol, xtol, gtol, method):
107
+ def check(tol, name):
108
+ if tol is None:
109
+ tol = 0
110
+ elif tol < EPS:
111
+ warn(f"Setting `{name}` below the machine epsilon ({EPS:.2e}) effectively "
112
+ f"disables the corresponding termination condition.",
113
+ stacklevel=3)
114
+ return tol
115
+
116
+ ftol = check(ftol, "ftol")
117
+ xtol = check(xtol, "xtol")
118
+ gtol = check(gtol, "gtol")
119
+
120
+ if method == "lm" and (ftol < EPS or xtol < EPS or gtol < EPS):
121
+ raise ValueError("All tolerances must be higher than machine epsilon "
122
+ f"({EPS:.2e}) for method 'lm'.")
123
+ elif ftol < EPS and xtol < EPS and gtol < EPS:
124
+ raise ValueError("At least one of the tolerances must be higher than "
125
+ f"machine epsilon ({EPS:.2e}).")
126
+
127
+ return ftol, xtol, gtol
128
+
129
+
130
+ def check_x_scale(x_scale, x0):
131
+ if isinstance(x_scale, str) and x_scale == 'jac':
132
+ return x_scale
133
+
134
+ try:
135
+ x_scale = np.asarray(x_scale, dtype=float)
136
+ valid = np.all(np.isfinite(x_scale)) and np.all(x_scale > 0)
137
+ except (ValueError, TypeError):
138
+ valid = False
139
+
140
+ if not valid:
141
+ raise ValueError("`x_scale` must be 'jac' or array_like with "
142
+ "positive numbers.")
143
+
144
+ if x_scale.ndim == 0:
145
+ x_scale = np.resize(x_scale, x0.shape)
146
+
147
+ if x_scale.shape != x0.shape:
148
+ raise ValueError("Inconsistent shapes between `x_scale` and `x0`.")
149
+
150
+ return x_scale
151
+
152
+
153
+ def check_jac_sparsity(jac_sparsity, m, n):
154
+ if jac_sparsity is None:
155
+ return None
156
+
157
+ if not issparse(jac_sparsity):
158
+ jac_sparsity = np.atleast_2d(jac_sparsity)
159
+
160
+ if jac_sparsity.shape != (m, n):
161
+ raise ValueError("`jac_sparsity` has wrong shape.")
162
+
163
+ return jac_sparsity, group_columns(jac_sparsity)
164
+
165
+
166
+ # Loss functions.
167
+
168
+
169
+ def huber(z, rho, cost_only):
170
+ mask = z <= 1
171
+ rho[0, mask] = z[mask]
172
+ rho[0, ~mask] = 2 * z[~mask]**0.5 - 1
173
+ if cost_only:
174
+ return
175
+ rho[1, mask] = 1
176
+ rho[1, ~mask] = z[~mask]**-0.5
177
+ rho[2, mask] = 0
178
+ rho[2, ~mask] = -0.5 * z[~mask]**-1.5
179
+
180
+
181
+ def soft_l1(z, rho, cost_only):
182
+ t = 1 + z
183
+ rho[0] = 2 * (t**0.5 - 1)
184
+ if cost_only:
185
+ return
186
+ rho[1] = t**-0.5
187
+ rho[2] = -0.5 * t**-1.5
188
+
189
+
190
+ def cauchy(z, rho, cost_only):
191
+ rho[0] = np.log1p(z)
192
+ if cost_only:
193
+ return
194
+ t = 1 + z
195
+ rho[1] = 1 / t
196
+ rho[2] = -1 / t**2
197
+
198
+
199
+ def arctan(z, rho, cost_only):
200
+ rho[0] = np.arctan(z)
201
+ if cost_only:
202
+ return
203
+ t = 1 + z**2
204
+ rho[1] = 1 / t
205
+ rho[2] = -2 * z / t**2
206
+
207
+
208
+ IMPLEMENTED_LOSSES = dict(linear=None, huber=huber, soft_l1=soft_l1,
209
+ cauchy=cauchy, arctan=arctan)
210
+
211
+
212
+ def construct_loss_function(m, loss, f_scale):
213
+ if loss == 'linear':
214
+ return None
215
+
216
+ if not callable(loss):
217
+ loss = IMPLEMENTED_LOSSES[loss]
218
+ rho = np.empty((3, m))
219
+
220
+ def loss_function(f, cost_only=False):
221
+ z = (f / f_scale) ** 2
222
+ loss(z, rho, cost_only=cost_only)
223
+ if cost_only:
224
+ return 0.5 * f_scale ** 2 * np.sum(rho[0])
225
+ rho[0] *= f_scale ** 2
226
+ rho[2] /= f_scale ** 2
227
+ return rho
228
+ else:
229
+ def loss_function(f, cost_only=False):
230
+ z = (f / f_scale) ** 2
231
+ rho = loss(z)
232
+ if cost_only:
233
+ return 0.5 * f_scale ** 2 * np.sum(rho[0])
234
+ rho[0] *= f_scale ** 2
235
+ rho[2] /= f_scale ** 2
236
+ return rho
237
+
238
+ return loss_function
239
+
240
+
241
+ def least_squares(
242
+ fun, x0, jac='2-point', bounds=(-np.inf, np.inf), method='trf',
243
+ ftol=1e-8, xtol=1e-8, gtol=1e-8, x_scale=1.0, loss='linear',
244
+ f_scale=1.0, diff_step=None, tr_solver=None, tr_options={},
245
+ jac_sparsity=None, max_nfev=None, verbose=0, args=(), kwargs={}):
246
+ """Solve a nonlinear least-squares problem with bounds on the variables.
247
+
248
+ Given the residuals f(x) (an m-D real function of n real
249
+ variables) and the loss function rho(s) (a scalar function), `least_squares`
250
+ finds a local minimum of the cost function F(x)::
251
+
252
+ minimize F(x) = 0.5 * sum(rho(f_i(x)**2), i = 0, ..., m - 1)
253
+ subject to lb <= x <= ub
254
+
255
+ The purpose of the loss function rho(s) is to reduce the influence of
256
+ outliers on the solution.
257
+
258
+ Parameters
259
+ ----------
260
+ fun : callable
261
+ Function which computes the vector of residuals, with the signature
262
+ ``fun(x, *args, **kwargs)``, i.e., the minimization proceeds with
263
+ respect to its first argument. The argument ``x`` passed to this
264
+ function is an ndarray of shape (n,) (never a scalar, even for n=1).
265
+ It must allocate and return a 1-D array_like of shape (m,) or a scalar.
266
+ If the argument ``x`` is complex or the function ``fun`` returns
267
+ complex residuals, it must be wrapped in a real function of real
268
+ arguments, as shown at the end of the Examples section.
269
+ x0 : array_like with shape (n,) or float
270
+ Initial guess on independent variables. If float, it will be treated
271
+ as a 1-D array with one element. When `method` is 'trf', the initial
272
+ guess might be slightly adjusted to lie sufficiently within the given
273
+ `bounds`.
274
+ jac : {'2-point', '3-point', 'cs', callable}, optional
275
+ Method of computing the Jacobian matrix (an m-by-n matrix, where
276
+ element (i, j) is the partial derivative of f[i] with respect to
277
+ x[j]). The keywords select a finite difference scheme for numerical
278
+ estimation. The scheme '3-point' is more accurate, but requires
279
+ twice as many operations as '2-point' (default). The scheme 'cs'
280
+ uses complex steps, and while potentially the most accurate, it is
281
+ applicable only when `fun` correctly handles complex inputs and
282
+ can be analytically continued to the complex plane. Method 'lm'
283
+ always uses the '2-point' scheme. If callable, it is used as
284
+ ``jac(x, *args, **kwargs)`` and should return a good approximation
285
+ (or the exact value) for the Jacobian as an array_like (np.atleast_2d
286
+ is applied), a sparse matrix (csr_matrix preferred for performance) or
287
+ a `scipy.sparse.linalg.LinearOperator`.
288
+ bounds : 2-tuple of array_like or `Bounds`, optional
289
+ There are two ways to specify bounds:
290
+
291
+ 1. Instance of `Bounds` class
292
+ 2. Lower and upper bounds on independent variables. Defaults to no
293
+ bounds. Each array must match the size of `x0` or be a scalar,
294
+ in the latter case a bound will be the same for all variables.
295
+ Use ``np.inf`` with an appropriate sign to disable bounds on all
296
+ or some variables.
297
+ method : {'trf', 'dogbox', 'lm'}, optional
298
+ Algorithm to perform minimization.
299
+
300
+ * 'trf' : Trust Region Reflective algorithm, particularly suitable
301
+ for large sparse problems with bounds. Generally robust method.
302
+ * 'dogbox' : dogleg algorithm with rectangular trust regions,
303
+ typical use case is small problems with bounds. Not recommended
304
+ for problems with rank-deficient Jacobian.
305
+ * 'lm' : Levenberg-Marquardt algorithm as implemented in MINPACK.
306
+ Doesn't handle bounds and sparse Jacobians. Usually the most
307
+ efficient method for small unconstrained problems.
308
+
309
+ Default is 'trf'. See Notes for more information.
310
+ ftol : float or None, optional
311
+ Tolerance for termination by the change of the cost function. Default
312
+ is 1e-8. The optimization process is stopped when ``dF < ftol * F``,
313
+ and there was an adequate agreement between a local quadratic model and
314
+ the true model in the last step.
315
+
316
+ If None and 'method' is not 'lm', the termination by this condition is
317
+ disabled. If 'method' is 'lm', this tolerance must be higher than
318
+ machine epsilon.
319
+ xtol : float or None, optional
320
+ Tolerance for termination by the change of the independent variables.
321
+ Default is 1e-8. The exact condition depends on the `method` used:
322
+
323
+ * For 'trf' and 'dogbox' : ``norm(dx) < xtol * (xtol + norm(x))``.
324
+ * For 'lm' : ``Delta < xtol * norm(xs)``, where ``Delta`` is
325
+ a trust-region radius and ``xs`` is the value of ``x``
326
+ scaled according to `x_scale` parameter (see below).
327
+
328
+ If None and 'method' is not 'lm', the termination by this condition is
329
+ disabled. If 'method' is 'lm', this tolerance must be higher than
330
+ machine epsilon.
331
+ gtol : float or None, optional
332
+ Tolerance for termination by the norm of the gradient. Default is 1e-8.
333
+ The exact condition depends on a `method` used:
334
+
335
+ * For 'trf' : ``norm(g_scaled, ord=np.inf) < gtol``, where
336
+ ``g_scaled`` is the value of the gradient scaled to account for
337
+ the presence of the bounds [STIR]_.
338
+ * For 'dogbox' : ``norm(g_free, ord=np.inf) < gtol``, where
339
+ ``g_free`` is the gradient with respect to the variables which
340
+ are not in the optimal state on the boundary.
341
+ * For 'lm' : the maximum absolute value of the cosine of angles
342
+ between columns of the Jacobian and the residual vector is less
343
+ than `gtol`, or the residual vector is zero.
344
+
345
+ If None and 'method' is not 'lm', the termination by this condition is
346
+ disabled. If 'method' is 'lm', this tolerance must be higher than
347
+ machine epsilon.
348
+ x_scale : array_like or 'jac', optional
349
+ Characteristic scale of each variable. Setting `x_scale` is equivalent
350
+ to reformulating the problem in scaled variables ``xs = x / x_scale``.
351
+ An alternative view is that the size of a trust region along jth
352
+ dimension is proportional to ``x_scale[j]``. Improved convergence may
353
+ be achieved by setting `x_scale` such that a step of a given size
354
+ along any of the scaled variables has a similar effect on the cost
355
+ function. If set to 'jac', the scale is iteratively updated using the
356
+ inverse norms of the columns of the Jacobian matrix (as described in
357
+ [JJMore]_).
358
+ loss : str or callable, optional
359
+ Determines the loss function. The following keyword values are allowed:
360
+
361
+ * 'linear' (default) : ``rho(z) = z``. Gives a standard
362
+ least-squares problem.
363
+ * 'soft_l1' : ``rho(z) = 2 * ((1 + z)**0.5 - 1)``. The smooth
364
+ approximation of l1 (absolute value) loss. Usually a good
365
+ choice for robust least squares.
366
+ * 'huber' : ``rho(z) = z if z <= 1 else 2*z**0.5 - 1``. Works
367
+ similarly to 'soft_l1'.
368
+ * 'cauchy' : ``rho(z) = ln(1 + z)``. Severely weakens outliers
369
+ influence, but may cause difficulties in optimization process.
370
+ * 'arctan' : ``rho(z) = arctan(z)``. Limits a maximum loss on
371
+ a single residual, has properties similar to 'cauchy'.
372
+
373
+ If callable, it must take a 1-D ndarray ``z=f**2`` and return an
374
+ array_like with shape (3, m) where row 0 contains function values,
375
+ row 1 contains first derivatives and row 2 contains second
376
+ derivatives. Method 'lm' supports only 'linear' loss.
377
+ f_scale : float, optional
378
+ Value of soft margin between inlier and outlier residuals, default
379
+ is 1.0. The loss function is evaluated as follows
380
+ ``rho_(f**2) = C**2 * rho(f**2 / C**2)``, where ``C`` is `f_scale`,
381
+ and ``rho`` is determined by `loss` parameter. This parameter has
382
+ no effect with ``loss='linear'``, but for other `loss` values it is
383
+ of crucial importance.
384
+ max_nfev : None or int, optional
385
+ Maximum number of function evaluations before the termination.
386
+ If None (default), the value is chosen automatically:
387
+
388
+ * For 'trf' and 'dogbox' : 100 * n.
389
+ * For 'lm' : 100 * n if `jac` is callable and 100 * n * (n + 1)
390
+ otherwise (because 'lm' counts function calls in Jacobian
391
+ estimation).
392
+
393
+ diff_step : None or array_like, optional
394
+ Determines the relative step size for the finite difference
395
+ approximation of the Jacobian. The actual step is computed as
396
+ ``x * diff_step``. If None (default), then `diff_step` is taken to be
397
+ a conventional "optimal" power of machine epsilon for the finite
398
+ difference scheme used [NR]_.
399
+ tr_solver : {None, 'exact', 'lsmr'}, optional
400
+ Method for solving trust-region subproblems, relevant only for 'trf'
401
+ and 'dogbox' methods.
402
+
403
+ * 'exact' is suitable for not very large problems with dense
404
+ Jacobian matrices. The computational complexity per iteration is
405
+ comparable to a singular value decomposition of the Jacobian
406
+ matrix.
407
+ * 'lsmr' is suitable for problems with sparse and large Jacobian
408
+ matrices. It uses the iterative procedure
409
+ `scipy.sparse.linalg.lsmr` for finding a solution of a linear
410
+ least-squares problem and only requires matrix-vector product
411
+ evaluations.
412
+
413
+ If None (default), the solver is chosen based on the type of Jacobian
414
+ returned on the first iteration.
415
+ tr_options : dict, optional
416
+ Keyword options passed to trust-region solver.
417
+
418
+ * ``tr_solver='exact'``: `tr_options` are ignored.
419
+ * ``tr_solver='lsmr'``: options for `scipy.sparse.linalg.lsmr`.
420
+ Additionally, ``method='trf'`` supports 'regularize' option
421
+ (bool, default is True), which adds a regularization term to the
422
+ normal equation, which improves convergence if the Jacobian is
423
+ rank-deficient [Byrd]_ (eq. 3.4).
424
+
425
+ jac_sparsity : {None, array_like, sparse matrix}, optional
426
+ Defines the sparsity structure of the Jacobian matrix for finite
427
+ difference estimation, its shape must be (m, n). If the Jacobian has
428
+ only few non-zero elements in *each* row, providing the sparsity
429
+ structure will greatly speed up the computations [Curtis]_. A zero
430
+ entry means that a corresponding element in the Jacobian is identically
431
+ zero. If provided, forces the use of 'lsmr' trust-region solver.
432
+ If None (default), then dense differencing will be used. Has no effect
433
+ for 'lm' method.
434
+ verbose : {0, 1, 2}, optional
435
+ Level of algorithm's verbosity:
436
+
437
+ * 0 (default) : work silently.
438
+ * 1 : display a termination report.
439
+ * 2 : display progress during iterations (not supported by 'lm'
440
+ method).
441
+
442
+ args, kwargs : tuple and dict, optional
443
+ Additional arguments passed to `fun` and `jac`. Both empty by default.
444
+ The calling signature is ``fun(x, *args, **kwargs)`` and the same for
445
+ `jac`.
446
+
447
+ Returns
448
+ -------
449
+ result : OptimizeResult
450
+ `OptimizeResult` with the following fields defined:
451
+
452
+ x : ndarray, shape (n,)
453
+ Solution found.
454
+ cost : float
455
+ Value of the cost function at the solution.
456
+ fun : ndarray, shape (m,)
457
+ Vector of residuals at the solution.
458
+ jac : ndarray, sparse matrix or LinearOperator, shape (m, n)
459
+ Modified Jacobian matrix at the solution, in the sense that J^T J
460
+ is a Gauss-Newton approximation of the Hessian of the cost function.
461
+ The type is the same as the one used by the algorithm.
462
+ grad : ndarray, shape (m,)
463
+ Gradient of the cost function at the solution.
464
+ optimality : float
465
+ First-order optimality measure. In unconstrained problems, it is
466
+ always the uniform norm of the gradient. In constrained problems,
467
+ it is the quantity which was compared with `gtol` during iterations.
468
+ active_mask : ndarray of int, shape (n,)
469
+ Each component shows whether a corresponding constraint is active
470
+ (that is, whether a variable is at the bound):
471
+
472
+ * 0 : a constraint is not active.
473
+ * -1 : a lower bound is active.
474
+ * 1 : an upper bound is active.
475
+
476
+ Might be somewhat arbitrary for 'trf' method as it generates a
477
+ sequence of strictly feasible iterates and `active_mask` is
478
+ determined within a tolerance threshold.
479
+ nfev : int
480
+ Number of function evaluations done. Methods 'trf' and 'dogbox' do
481
+ not count function calls for numerical Jacobian approximation, as
482
+ opposed to 'lm' method.
483
+ njev : int or None
484
+ Number of Jacobian evaluations done. If numerical Jacobian
485
+ approximation is used in 'lm' method, it is set to None.
486
+ status : int
487
+ The reason for algorithm termination:
488
+
489
+ * -1 : improper input parameters status returned from MINPACK.
490
+ * 0 : the maximum number of function evaluations is exceeded.
491
+ * 1 : `gtol` termination condition is satisfied.
492
+ * 2 : `ftol` termination condition is satisfied.
493
+ * 3 : `xtol` termination condition is satisfied.
494
+ * 4 : Both `ftol` and `xtol` termination conditions are satisfied.
495
+
496
+ message : str
497
+ Verbal description of the termination reason.
498
+ success : bool
499
+ True if one of the convergence criteria is satisfied (`status` > 0).
500
+
501
+ See Also
502
+ --------
503
+ leastsq : A legacy wrapper for the MINPACK implementation of the
504
+ Levenberg-Marquadt algorithm.
505
+ curve_fit : Least-squares minimization applied to a curve-fitting problem.
506
+
507
+ Notes
508
+ -----
509
+ Method 'lm' (Levenberg-Marquardt) calls a wrapper over least-squares
510
+ algorithms implemented in MINPACK (lmder, lmdif). It runs the
511
+ Levenberg-Marquardt algorithm formulated as a trust-region type algorithm.
512
+ The implementation is based on paper [JJMore]_, it is very robust and
513
+ efficient with a lot of smart tricks. It should be your first choice
514
+ for unconstrained problems. Note that it doesn't support bounds. Also,
515
+ it doesn't work when m < n.
516
+
517
+ Method 'trf' (Trust Region Reflective) is motivated by the process of
518
+ solving a system of equations, which constitute the first-order optimality
519
+ condition for a bound-constrained minimization problem as formulated in
520
+ [STIR]_. The algorithm iteratively solves trust-region subproblems
521
+ augmented by a special diagonal quadratic term and with trust-region shape
522
+ determined by the distance from the bounds and the direction of the
523
+ gradient. This enhancements help to avoid making steps directly into bounds
524
+ and efficiently explore the whole space of variables. To further improve
525
+ convergence, the algorithm considers search directions reflected from the
526
+ bounds. To obey theoretical requirements, the algorithm keeps iterates
527
+ strictly feasible. With dense Jacobians trust-region subproblems are
528
+ solved by an exact method very similar to the one described in [JJMore]_
529
+ (and implemented in MINPACK). The difference from the MINPACK
530
+ implementation is that a singular value decomposition of a Jacobian
531
+ matrix is done once per iteration, instead of a QR decomposition and series
532
+ of Givens rotation eliminations. For large sparse Jacobians a 2-D subspace
533
+ approach of solving trust-region subproblems is used [STIR]_, [Byrd]_.
534
+ The subspace is spanned by a scaled gradient and an approximate
535
+ Gauss-Newton solution delivered by `scipy.sparse.linalg.lsmr`. When no
536
+ constraints are imposed the algorithm is very similar to MINPACK and has
537
+ generally comparable performance. The algorithm works quite robust in
538
+ unbounded and bounded problems, thus it is chosen as a default algorithm.
539
+
540
+ Method 'dogbox' operates in a trust-region framework, but considers
541
+ rectangular trust regions as opposed to conventional ellipsoids [Voglis]_.
542
+ The intersection of a current trust region and initial bounds is again
543
+ rectangular, so on each iteration a quadratic minimization problem subject
544
+ to bound constraints is solved approximately by Powell's dogleg method
545
+ [NumOpt]_. The required Gauss-Newton step can be computed exactly for
546
+ dense Jacobians or approximately by `scipy.sparse.linalg.lsmr` for large
547
+ sparse Jacobians. The algorithm is likely to exhibit slow convergence when
548
+ the rank of Jacobian is less than the number of variables. The algorithm
549
+ often outperforms 'trf' in bounded problems with a small number of
550
+ variables.
551
+
552
+ Robust loss functions are implemented as described in [BA]_. The idea
553
+ is to modify a residual vector and a Jacobian matrix on each iteration
554
+ such that computed gradient and Gauss-Newton Hessian approximation match
555
+ the true gradient and Hessian approximation of the cost function. Then
556
+ the algorithm proceeds in a normal way, i.e., robust loss functions are
557
+ implemented as a simple wrapper over standard least-squares algorithms.
558
+
559
+ .. versionadded:: 0.17.0
560
+
561
+ References
562
+ ----------
563
+ .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior,
564
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
565
+ Minimization Problems," SIAM Journal on Scientific Computing,
566
+ Vol. 21, Number 1, pp 1-23, 1999.
567
+ .. [NR] William H. Press et. al., "Numerical Recipes. The Art of Scientific
568
+ Computing. 3rd edition", Sec. 5.7.
569
+ .. [Byrd] R. H. Byrd, R. B. Schnabel and G. A. Shultz, "Approximate
570
+ solution of the trust region problem by minimization over
571
+ two-dimensional subspaces", Math. Programming, 40, pp. 247-263,
572
+ 1988.
573
+ .. [Curtis] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
574
+ sparse Jacobian matrices", Journal of the Institute of
575
+ Mathematics and its Applications, 13, pp. 117-120, 1974.
576
+ .. [JJMore] J. J. More, "The Levenberg-Marquardt Algorithm: Implementation
577
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
578
+ Notes in Mathematics 630, Springer Verlag, pp. 105-116, 1977.
579
+ .. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region
580
+ Dogleg Approach for Unconstrained and Bound Constrained
581
+ Nonlinear Optimization", WSEAS International Conference on
582
+ Applied Mathematics, Corfu, Greece, 2004.
583
+ .. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization,
584
+ 2nd edition", Chapter 4.
585
+ .. [BA] B. Triggs et. al., "Bundle Adjustment - A Modern Synthesis",
586
+ Proceedings of the International Workshop on Vision Algorithms:
587
+ Theory and Practice, pp. 298-372, 1999.
588
+
589
+ Examples
590
+ --------
591
+ In this example we find a minimum of the Rosenbrock function without bounds
592
+ on independent variables.
593
+
594
+ >>> import numpy as np
595
+ >>> def fun_rosenbrock(x):
596
+ ... return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])
597
+
598
+ Notice that we only provide the vector of the residuals. The algorithm
599
+ constructs the cost function as a sum of squares of the residuals, which
600
+ gives the Rosenbrock function. The exact minimum is at ``x = [1.0, 1.0]``.
601
+
602
+ >>> from scipy.optimize import least_squares
603
+ >>> x0_rosenbrock = np.array([2, 2])
604
+ >>> res_1 = least_squares(fun_rosenbrock, x0_rosenbrock)
605
+ >>> res_1.x
606
+ array([ 1., 1.])
607
+ >>> res_1.cost
608
+ 9.8669242910846867e-30
609
+ >>> res_1.optimality
610
+ 8.8928864934219529e-14
611
+
612
+ We now constrain the variables, in such a way that the previous solution
613
+ becomes infeasible. Specifically, we require that ``x[1] >= 1.5``, and
614
+ ``x[0]`` left unconstrained. To this end, we specify the `bounds` parameter
615
+ to `least_squares` in the form ``bounds=([-np.inf, 1.5], np.inf)``.
616
+
617
+ We also provide the analytic Jacobian:
618
+
619
+ >>> def jac_rosenbrock(x):
620
+ ... return np.array([
621
+ ... [-20 * x[0], 10],
622
+ ... [-1, 0]])
623
+
624
+ Putting this all together, we see that the new solution lies on the bound:
625
+
626
+ >>> res_2 = least_squares(fun_rosenbrock, x0_rosenbrock, jac_rosenbrock,
627
+ ... bounds=([-np.inf, 1.5], np.inf))
628
+ >>> res_2.x
629
+ array([ 1.22437075, 1.5 ])
630
+ >>> res_2.cost
631
+ 0.025213093946805685
632
+ >>> res_2.optimality
633
+ 1.5885401433157753e-07
634
+
635
+ Now we solve a system of equations (i.e., the cost function should be zero
636
+ at a minimum) for a Broyden tridiagonal vector-valued function of 100000
637
+ variables:
638
+
639
+ >>> def fun_broyden(x):
640
+ ... f = (3 - x) * x + 1
641
+ ... f[1:] -= x[:-1]
642
+ ... f[:-1] -= 2 * x[1:]
643
+ ... return f
644
+
645
+ The corresponding Jacobian matrix is sparse. We tell the algorithm to
646
+ estimate it by finite differences and provide the sparsity structure of
647
+ Jacobian to significantly speed up this process.
648
+
649
+ >>> from scipy.sparse import lil_matrix
650
+ >>> def sparsity_broyden(n):
651
+ ... sparsity = lil_matrix((n, n), dtype=int)
652
+ ... i = np.arange(n)
653
+ ... sparsity[i, i] = 1
654
+ ... i = np.arange(1, n)
655
+ ... sparsity[i, i - 1] = 1
656
+ ... i = np.arange(n - 1)
657
+ ... sparsity[i, i + 1] = 1
658
+ ... return sparsity
659
+ ...
660
+ >>> n = 100000
661
+ >>> x0_broyden = -np.ones(n)
662
+ ...
663
+ >>> res_3 = least_squares(fun_broyden, x0_broyden,
664
+ ... jac_sparsity=sparsity_broyden(n))
665
+ >>> res_3.cost
666
+ 4.5687069299604613e-23
667
+ >>> res_3.optimality
668
+ 1.1650454296851518e-11
669
+
670
+ Let's also solve a curve fitting problem using robust loss function to
671
+ take care of outliers in the data. Define the model function as
672
+ ``y = a + b * exp(c * t)``, where t is a predictor variable, y is an
673
+ observation and a, b, c are parameters to estimate.
674
+
675
+ First, define the function which generates the data with noise and
676
+ outliers, define the model parameters, and generate data:
677
+
678
+ >>> from numpy.random import default_rng
679
+ >>> rng = default_rng()
680
+ >>> def gen_data(t, a, b, c, noise=0., n_outliers=0, seed=None):
681
+ ... rng = default_rng(seed)
682
+ ...
683
+ ... y = a + b * np.exp(t * c)
684
+ ...
685
+ ... error = noise * rng.standard_normal(t.size)
686
+ ... outliers = rng.integers(0, t.size, n_outliers)
687
+ ... error[outliers] *= 10
688
+ ...
689
+ ... return y + error
690
+ ...
691
+ >>> a = 0.5
692
+ >>> b = 2.0
693
+ >>> c = -1
694
+ >>> t_min = 0
695
+ >>> t_max = 10
696
+ >>> n_points = 15
697
+ ...
698
+ >>> t_train = np.linspace(t_min, t_max, n_points)
699
+ >>> y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3)
700
+
701
+ Define function for computing residuals and initial estimate of
702
+ parameters.
703
+
704
+ >>> def fun(x, t, y):
705
+ ... return x[0] + x[1] * np.exp(x[2] * t) - y
706
+ ...
707
+ >>> x0 = np.array([1.0, 1.0, 0.0])
708
+
709
+ Compute a standard least-squares solution:
710
+
711
+ >>> res_lsq = least_squares(fun, x0, args=(t_train, y_train))
712
+
713
+ Now compute two solutions with two different robust loss functions. The
714
+ parameter `f_scale` is set to 0.1, meaning that inlier residuals should
715
+ not significantly exceed 0.1 (the noise level used).
716
+
717
+ >>> res_soft_l1 = least_squares(fun, x0, loss='soft_l1', f_scale=0.1,
718
+ ... args=(t_train, y_train))
719
+ >>> res_log = least_squares(fun, x0, loss='cauchy', f_scale=0.1,
720
+ ... args=(t_train, y_train))
721
+
722
+ And, finally, plot all the curves. We see that by selecting an appropriate
723
+ `loss` we can get estimates close to optimal even in the presence of
724
+ strong outliers. But keep in mind that generally it is recommended to try
725
+ 'soft_l1' or 'huber' losses first (if at all necessary) as the other two
726
+ options may cause difficulties in optimization process.
727
+
728
+ >>> t_test = np.linspace(t_min, t_max, n_points * 10)
729
+ >>> y_true = gen_data(t_test, a, b, c)
730
+ >>> y_lsq = gen_data(t_test, *res_lsq.x)
731
+ >>> y_soft_l1 = gen_data(t_test, *res_soft_l1.x)
732
+ >>> y_log = gen_data(t_test, *res_log.x)
733
+ ...
734
+ >>> import matplotlib.pyplot as plt
735
+ >>> plt.plot(t_train, y_train, 'o')
736
+ >>> plt.plot(t_test, y_true, 'k', linewidth=2, label='true')
737
+ >>> plt.plot(t_test, y_lsq, label='linear loss')
738
+ >>> plt.plot(t_test, y_soft_l1, label='soft_l1 loss')
739
+ >>> plt.plot(t_test, y_log, label='cauchy loss')
740
+ >>> plt.xlabel("t")
741
+ >>> plt.ylabel("y")
742
+ >>> plt.legend()
743
+ >>> plt.show()
744
+
745
+ In the next example, we show how complex-valued residual functions of
746
+ complex variables can be optimized with ``least_squares()``. Consider the
747
+ following function:
748
+
749
+ >>> def f(z):
750
+ ... return z - (0.5 + 0.5j)
751
+
752
+ We wrap it into a function of real variables that returns real residuals
753
+ by simply handling the real and imaginary parts as independent variables:
754
+
755
+ >>> def f_wrap(x):
756
+ ... fx = f(x[0] + 1j*x[1])
757
+ ... return np.array([fx.real, fx.imag])
758
+
759
+ Thus, instead of the original m-D complex function of n complex
760
+ variables we optimize a 2m-D real function of 2n real variables:
761
+
762
+ >>> from scipy.optimize import least_squares
763
+ >>> res_wrapped = least_squares(f_wrap, (0.1, 0.1), bounds=([0, 0], [1, 1]))
764
+ >>> z = res_wrapped.x[0] + res_wrapped.x[1]*1j
765
+ >>> z
766
+ (0.49999999999925893+0.49999999999925893j)
767
+
768
+ """
769
+ if method not in ['trf', 'dogbox', 'lm']:
770
+ raise ValueError("`method` must be 'trf', 'dogbox' or 'lm'.")
771
+
772
+ if jac not in ['2-point', '3-point', 'cs'] and not callable(jac):
773
+ raise ValueError("`jac` must be '2-point', '3-point', 'cs' or "
774
+ "callable.")
775
+
776
+ if tr_solver not in [None, 'exact', 'lsmr']:
777
+ raise ValueError("`tr_solver` must be None, 'exact' or 'lsmr'.")
778
+
779
+ if loss not in IMPLEMENTED_LOSSES and not callable(loss):
780
+ raise ValueError("`loss` must be one of {} or a callable."
781
+ .format(IMPLEMENTED_LOSSES.keys()))
782
+
783
+ if method == 'lm' and loss != 'linear':
784
+ raise ValueError("method='lm' supports only 'linear' loss function.")
785
+
786
+ if verbose not in [0, 1, 2]:
787
+ raise ValueError("`verbose` must be in [0, 1, 2].")
788
+
789
+ if max_nfev is not None and max_nfev <= 0:
790
+ raise ValueError("`max_nfev` must be None or positive integer.")
791
+
792
+ if np.iscomplexobj(x0):
793
+ raise ValueError("`x0` must be real.")
794
+
795
+ x0 = np.atleast_1d(x0).astype(float)
796
+
797
+ if x0.ndim > 1:
798
+ raise ValueError("`x0` must have at most 1 dimension.")
799
+
800
+ if isinstance(bounds, Bounds):
801
+ lb, ub = bounds.lb, bounds.ub
802
+ bounds = (lb, ub)
803
+ else:
804
+ if len(bounds) == 2:
805
+ lb, ub = prepare_bounds(bounds, x0.shape[0])
806
+ else:
807
+ raise ValueError("`bounds` must contain 2 elements.")
808
+
809
+ if method == 'lm' and not np.all((lb == -np.inf) & (ub == np.inf)):
810
+ raise ValueError("Method 'lm' doesn't support bounds.")
811
+
812
+ if lb.shape != x0.shape or ub.shape != x0.shape:
813
+ raise ValueError("Inconsistent shapes between bounds and `x0`.")
814
+
815
+ if np.any(lb >= ub):
816
+ raise ValueError("Each lower bound must be strictly less than each "
817
+ "upper bound.")
818
+
819
+ if not in_bounds(x0, lb, ub):
820
+ raise ValueError("`x0` is infeasible.")
821
+
822
+ x_scale = check_x_scale(x_scale, x0)
823
+
824
+ ftol, xtol, gtol = check_tolerance(ftol, xtol, gtol, method)
825
+
826
+ if method == 'trf':
827
+ x0 = make_strictly_feasible(x0, lb, ub)
828
+
829
+ def fun_wrapped(x):
830
+ return np.atleast_1d(fun(x, *args, **kwargs))
831
+
832
+ f0 = fun_wrapped(x0)
833
+
834
+ if f0.ndim != 1:
835
+ raise ValueError("`fun` must return at most 1-d array_like. "
836
+ f"f0.shape: {f0.shape}")
837
+
838
+ if not np.all(np.isfinite(f0)):
839
+ raise ValueError("Residuals are not finite in the initial point.")
840
+
841
+ n = x0.size
842
+ m = f0.size
843
+
844
+ if method == 'lm' and m < n:
845
+ raise ValueError("Method 'lm' doesn't work when the number of "
846
+ "residuals is less than the number of variables.")
847
+
848
+ loss_function = construct_loss_function(m, loss, f_scale)
849
+ if callable(loss):
850
+ rho = loss_function(f0)
851
+ if rho.shape != (3, m):
852
+ raise ValueError("The return value of `loss` callable has wrong "
853
+ "shape.")
854
+ initial_cost = 0.5 * np.sum(rho[0])
855
+ elif loss_function is not None:
856
+ initial_cost = loss_function(f0, cost_only=True)
857
+ else:
858
+ initial_cost = 0.5 * np.dot(f0, f0)
859
+
860
+ if callable(jac):
861
+ J0 = jac(x0, *args, **kwargs)
862
+
863
+ if issparse(J0):
864
+ J0 = J0.tocsr()
865
+
866
+ def jac_wrapped(x, _=None):
867
+ return jac(x, *args, **kwargs).tocsr()
868
+
869
+ elif isinstance(J0, LinearOperator):
870
+ def jac_wrapped(x, _=None):
871
+ return jac(x, *args, **kwargs)
872
+
873
+ else:
874
+ J0 = np.atleast_2d(J0)
875
+
876
+ def jac_wrapped(x, _=None):
877
+ return np.atleast_2d(jac(x, *args, **kwargs))
878
+
879
+ else: # Estimate Jacobian by finite differences.
880
+ if method == 'lm':
881
+ if jac_sparsity is not None:
882
+ raise ValueError("method='lm' does not support "
883
+ "`jac_sparsity`.")
884
+
885
+ if jac != '2-point':
886
+ warn(f"jac='{jac}' works equivalently to '2-point' for method='lm'.",
887
+ stacklevel=2)
888
+
889
+ J0 = jac_wrapped = None
890
+ else:
891
+ if jac_sparsity is not None and tr_solver == 'exact':
892
+ raise ValueError("tr_solver='exact' is incompatible "
893
+ "with `jac_sparsity`.")
894
+
895
+ jac_sparsity = check_jac_sparsity(jac_sparsity, m, n)
896
+
897
+ def jac_wrapped(x, f):
898
+ J = approx_derivative(fun, x, rel_step=diff_step, method=jac,
899
+ f0=f, bounds=bounds, args=args,
900
+ kwargs=kwargs, sparsity=jac_sparsity)
901
+ if J.ndim != 2: # J is guaranteed not sparse.
902
+ J = np.atleast_2d(J)
903
+
904
+ return J
905
+
906
+ J0 = jac_wrapped(x0, f0)
907
+
908
+ if J0 is not None:
909
+ if J0.shape != (m, n):
910
+ raise ValueError(
911
+ f"The return value of `jac` has wrong shape: expected {(m, n)}, "
912
+ f"actual {J0.shape}."
913
+ )
914
+
915
+ if not isinstance(J0, np.ndarray):
916
+ if method == 'lm':
917
+ raise ValueError("method='lm' works only with dense "
918
+ "Jacobian matrices.")
919
+
920
+ if tr_solver == 'exact':
921
+ raise ValueError(
922
+ "tr_solver='exact' works only with dense "
923
+ "Jacobian matrices.")
924
+
925
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
926
+ if isinstance(J0, LinearOperator) and jac_scale:
927
+ raise ValueError("x_scale='jac' can't be used when `jac` "
928
+ "returns LinearOperator.")
929
+
930
+ if tr_solver is None:
931
+ if isinstance(J0, np.ndarray):
932
+ tr_solver = 'exact'
933
+ else:
934
+ tr_solver = 'lsmr'
935
+
936
+ if method == 'lm':
937
+ result = call_minpack(fun_wrapped, x0, jac_wrapped, ftol, xtol, gtol,
938
+ max_nfev, x_scale, diff_step)
939
+
940
+ elif method == 'trf':
941
+ result = trf(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol, xtol,
942
+ gtol, max_nfev, x_scale, loss_function, tr_solver,
943
+ tr_options.copy(), verbose)
944
+
945
+ elif method == 'dogbox':
946
+ if tr_solver == 'lsmr' and 'regularize' in tr_options:
947
+ warn("The keyword 'regularize' in `tr_options` is not relevant "
948
+ "for 'dogbox' method.",
949
+ stacklevel=2)
950
+ tr_options = tr_options.copy()
951
+ del tr_options['regularize']
952
+
953
+ result = dogbox(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol,
954
+ xtol, gtol, max_nfev, x_scale, loss_function,
955
+ tr_solver, tr_options, verbose)
956
+
957
+ result.message = TERMINATION_MESSAGES[result.status]
958
+ result.success = result.status > 0
959
+
960
+ if verbose >= 1:
961
+ print(result.message)
962
+ print("Function evaluations {}, initial cost {:.4e}, final cost "
963
+ "{:.4e}, first-order optimality {:.2e}."
964
+ .format(result.nfev, initial_cost, result.cost,
965
+ result.optimality))
966
+
967
+ return result
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/lsq_linear.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Linear least squares with bound constraints on independent variables."""
2
+ import numpy as np
3
+ from numpy.linalg import norm
4
+ from scipy.sparse import issparse, csr_matrix
5
+ from scipy.sparse.linalg import LinearOperator, lsmr
6
+ from scipy.optimize import OptimizeResult
7
+ from scipy.optimize._minimize import Bounds
8
+
9
+ from .common import in_bounds, compute_grad
10
+ from .trf_linear import trf_linear
11
+ from .bvls import bvls
12
+
13
+
14
+ def prepare_bounds(bounds, n):
15
+ if len(bounds) != 2:
16
+ raise ValueError("`bounds` must contain 2 elements.")
17
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
18
+
19
+ if lb.ndim == 0:
20
+ lb = np.resize(lb, n)
21
+
22
+ if ub.ndim == 0:
23
+ ub = np.resize(ub, n)
24
+
25
+ return lb, ub
26
+
27
+
28
+ TERMINATION_MESSAGES = {
29
+ -1: "The algorithm was not able to make progress on the last iteration.",
30
+ 0: "The maximum number of iterations is exceeded.",
31
+ 1: "The first-order optimality measure is less than `tol`.",
32
+ 2: "The relative change of the cost function is less than `tol`.",
33
+ 3: "The unconstrained solution is optimal."
34
+ }
35
+
36
+
37
+ def lsq_linear(A, b, bounds=(-np.inf, np.inf), method='trf', tol=1e-10,
38
+ lsq_solver=None, lsmr_tol=None, max_iter=None,
39
+ verbose=0, *, lsmr_maxiter=None,):
40
+ r"""Solve a linear least-squares problem with bounds on the variables.
41
+
42
+ Given a m-by-n design matrix A and a target vector b with m elements,
43
+ `lsq_linear` solves the following optimization problem::
44
+
45
+ minimize 0.5 * ||A x - b||**2
46
+ subject to lb <= x <= ub
47
+
48
+ This optimization problem is convex, hence a found minimum (if iterations
49
+ have converged) is guaranteed to be global.
50
+
51
+ Parameters
52
+ ----------
53
+ A : array_like, sparse matrix of LinearOperator, shape (m, n)
54
+ Design matrix. Can be `scipy.sparse.linalg.LinearOperator`.
55
+ b : array_like, shape (m,)
56
+ Target vector.
57
+ bounds : 2-tuple of array_like or `Bounds`, optional
58
+ Lower and upper bounds on parameters. Defaults to no bounds.
59
+ There are two ways to specify the bounds:
60
+
61
+ - Instance of `Bounds` class.
62
+
63
+ - 2-tuple of array_like: Each element of the tuple must be either
64
+ an array with the length equal to the number of parameters, or a
65
+ scalar (in which case the bound is taken to be the same for all
66
+ parameters). Use ``np.inf`` with an appropriate sign to disable
67
+ bounds on all or some parameters.
68
+
69
+ method : 'trf' or 'bvls', optional
70
+ Method to perform minimization.
71
+
72
+ * 'trf' : Trust Region Reflective algorithm adapted for a linear
73
+ least-squares problem. This is an interior-point-like method
74
+ and the required number of iterations is weakly correlated with
75
+ the number of variables.
76
+ * 'bvls' : Bounded-variable least-squares algorithm. This is
77
+ an active set method, which requires the number of iterations
78
+ comparable to the number of variables. Can't be used when `A` is
79
+ sparse or LinearOperator.
80
+
81
+ Default is 'trf'.
82
+ tol : float, optional
83
+ Tolerance parameter. The algorithm terminates if a relative change
84
+ of the cost function is less than `tol` on the last iteration.
85
+ Additionally, the first-order optimality measure is considered:
86
+
87
+ * ``method='trf'`` terminates if the uniform norm of the gradient,
88
+ scaled to account for the presence of the bounds, is less than
89
+ `tol`.
90
+ * ``method='bvls'`` terminates if Karush-Kuhn-Tucker conditions
91
+ are satisfied within `tol` tolerance.
92
+
93
+ lsq_solver : {None, 'exact', 'lsmr'}, optional
94
+ Method of solving unbounded least-squares problems throughout
95
+ iterations:
96
+
97
+ * 'exact' : Use dense QR or SVD decomposition approach. Can't be
98
+ used when `A` is sparse or LinearOperator.
99
+ * 'lsmr' : Use `scipy.sparse.linalg.lsmr` iterative procedure
100
+ which requires only matrix-vector product evaluations. Can't
101
+ be used with ``method='bvls'``.
102
+
103
+ If None (default), the solver is chosen based on type of `A`.
104
+ lsmr_tol : None, float or 'auto', optional
105
+ Tolerance parameters 'atol' and 'btol' for `scipy.sparse.linalg.lsmr`
106
+ If None (default), it is set to ``1e-2 * tol``. If 'auto', the
107
+ tolerance will be adjusted based on the optimality of the current
108
+ iterate, which can speed up the optimization process, but is not always
109
+ reliable.
110
+ max_iter : None or int, optional
111
+ Maximum number of iterations before termination. If None (default), it
112
+ is set to 100 for ``method='trf'`` or to the number of variables for
113
+ ``method='bvls'`` (not counting iterations for 'bvls' initialization).
114
+ verbose : {0, 1, 2}, optional
115
+ Level of algorithm's verbosity:
116
+
117
+ * 0 : work silently (default).
118
+ * 1 : display a termination report.
119
+ * 2 : display progress during iterations.
120
+ lsmr_maxiter : None or int, optional
121
+ Maximum number of iterations for the lsmr least squares solver,
122
+ if it is used (by setting ``lsq_solver='lsmr'``). If None (default), it
123
+ uses lsmr's default of ``min(m, n)`` where ``m`` and ``n`` are the
124
+ number of rows and columns of `A`, respectively. Has no effect if
125
+ ``lsq_solver='exact'``.
126
+
127
+ Returns
128
+ -------
129
+ OptimizeResult with the following fields defined:
130
+ x : ndarray, shape (n,)
131
+ Solution found.
132
+ cost : float
133
+ Value of the cost function at the solution.
134
+ fun : ndarray, shape (m,)
135
+ Vector of residuals at the solution.
136
+ optimality : float
137
+ First-order optimality measure. The exact meaning depends on `method`,
138
+ refer to the description of `tol` parameter.
139
+ active_mask : ndarray of int, shape (n,)
140
+ Each component shows whether a corresponding constraint is active
141
+ (that is, whether a variable is at the bound):
142
+
143
+ * 0 : a constraint is not active.
144
+ * -1 : a lower bound is active.
145
+ * 1 : an upper bound is active.
146
+
147
+ Might be somewhat arbitrary for the `trf` method as it generates a
148
+ sequence of strictly feasible iterates and active_mask is determined
149
+ within a tolerance threshold.
150
+ unbounded_sol : tuple
151
+ Unbounded least squares solution tuple returned by the least squares
152
+ solver (set with `lsq_solver` option). If `lsq_solver` is not set or is
153
+ set to ``'exact'``, the tuple contains an ndarray of shape (n,) with
154
+ the unbounded solution, an ndarray with the sum of squared residuals,
155
+ an int with the rank of `A`, and an ndarray with the singular values
156
+ of `A` (see NumPy's ``linalg.lstsq`` for more information). If
157
+ `lsq_solver` is set to ``'lsmr'``, the tuple contains an ndarray of
158
+ shape (n,) with the unbounded solution, an int with the exit code,
159
+ an int with the number of iterations, and five floats with
160
+ various norms and the condition number of `A` (see SciPy's
161
+ ``sparse.linalg.lsmr`` for more information). This output can be
162
+ useful for determining the convergence of the least squares solver,
163
+ particularly the iterative ``'lsmr'`` solver. The unbounded least
164
+ squares problem is to minimize ``0.5 * ||A x - b||**2``.
165
+ nit : int
166
+ Number of iterations. Zero if the unconstrained solution is optimal.
167
+ status : int
168
+ Reason for algorithm termination:
169
+
170
+ * -1 : the algorithm was not able to make progress on the last
171
+ iteration.
172
+ * 0 : the maximum number of iterations is exceeded.
173
+ * 1 : the first-order optimality measure is less than `tol`.
174
+ * 2 : the relative change of the cost function is less than `tol`.
175
+ * 3 : the unconstrained solution is optimal.
176
+
177
+ message : str
178
+ Verbal description of the termination reason.
179
+ success : bool
180
+ True if one of the convergence criteria is satisfied (`status` > 0).
181
+
182
+ See Also
183
+ --------
184
+ nnls : Linear least squares with non-negativity constraint.
185
+ least_squares : Nonlinear least squares with bounds on the variables.
186
+
187
+ Notes
188
+ -----
189
+ The algorithm first computes the unconstrained least-squares solution by
190
+ `numpy.linalg.lstsq` or `scipy.sparse.linalg.lsmr` depending on
191
+ `lsq_solver`. This solution is returned as optimal if it lies within the
192
+ bounds.
193
+
194
+ Method 'trf' runs the adaptation of the algorithm described in [STIR]_ for
195
+ a linear least-squares problem. The iterations are essentially the same as
196
+ in the nonlinear least-squares algorithm, but as the quadratic function
197
+ model is always accurate, we don't need to track or modify the radius of
198
+ a trust region. The line search (backtracking) is used as a safety net
199
+ when a selected step does not decrease the cost function. Read more
200
+ detailed description of the algorithm in `scipy.optimize.least_squares`.
201
+
202
+ Method 'bvls' runs a Python implementation of the algorithm described in
203
+ [BVLS]_. The algorithm maintains active and free sets of variables, on
204
+ each iteration chooses a new variable to move from the active set to the
205
+ free set and then solves the unconstrained least-squares problem on free
206
+ variables. This algorithm is guaranteed to give an accurate solution
207
+ eventually, but may require up to n iterations for a problem with n
208
+ variables. Additionally, an ad-hoc initialization procedure is
209
+ implemented, that determines which variables to set free or active
210
+ initially. It takes some number of iterations before actual BVLS starts,
211
+ but can significantly reduce the number of further iterations.
212
+
213
+ References
214
+ ----------
215
+ .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior,
216
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
217
+ Minimization Problems," SIAM Journal on Scientific Computing,
218
+ Vol. 21, Number 1, pp 1-23, 1999.
219
+ .. [BVLS] P. B. Start and R. L. Parker, "Bounded-Variable Least-Squares:
220
+ an Algorithm and Applications", Computational Statistics, 10,
221
+ 129-141, 1995.
222
+
223
+ Examples
224
+ --------
225
+ In this example, a problem with a large sparse matrix and bounds on the
226
+ variables is solved.
227
+
228
+ >>> import numpy as np
229
+ >>> from scipy.sparse import rand
230
+ >>> from scipy.optimize import lsq_linear
231
+ >>> rng = np.random.default_rng()
232
+ ...
233
+ >>> m = 20000
234
+ >>> n = 10000
235
+ ...
236
+ >>> A = rand(m, n, density=1e-4, random_state=rng)
237
+ >>> b = rng.standard_normal(m)
238
+ ...
239
+ >>> lb = rng.standard_normal(n)
240
+ >>> ub = lb + 1
241
+ ...
242
+ >>> res = lsq_linear(A, b, bounds=(lb, ub), lsmr_tol='auto', verbose=1)
243
+ # may vary
244
+ The relative change of the cost function is less than `tol`.
245
+ Number of iterations 16, initial cost 1.5039e+04, final cost 1.1112e+04,
246
+ first-order optimality 4.66e-08.
247
+ """
248
+ if method not in ['trf', 'bvls']:
249
+ raise ValueError("`method` must be 'trf' or 'bvls'")
250
+
251
+ if lsq_solver not in [None, 'exact', 'lsmr']:
252
+ raise ValueError("`solver` must be None, 'exact' or 'lsmr'.")
253
+
254
+ if verbose not in [0, 1, 2]:
255
+ raise ValueError("`verbose` must be in [0, 1, 2].")
256
+
257
+ if issparse(A):
258
+ A = csr_matrix(A)
259
+ elif not isinstance(A, LinearOperator):
260
+ A = np.atleast_2d(np.asarray(A))
261
+
262
+ if method == 'bvls':
263
+ if lsq_solver == 'lsmr':
264
+ raise ValueError("method='bvls' can't be used with "
265
+ "lsq_solver='lsmr'")
266
+
267
+ if not isinstance(A, np.ndarray):
268
+ raise ValueError("method='bvls' can't be used with `A` being "
269
+ "sparse or LinearOperator.")
270
+
271
+ if lsq_solver is None:
272
+ if isinstance(A, np.ndarray):
273
+ lsq_solver = 'exact'
274
+ else:
275
+ lsq_solver = 'lsmr'
276
+ elif lsq_solver == 'exact' and not isinstance(A, np.ndarray):
277
+ raise ValueError("`exact` solver can't be used when `A` is "
278
+ "sparse or LinearOperator.")
279
+
280
+ if len(A.shape) != 2: # No ndim for LinearOperator.
281
+ raise ValueError("`A` must have at most 2 dimensions.")
282
+
283
+ if max_iter is not None and max_iter <= 0:
284
+ raise ValueError("`max_iter` must be None or positive integer.")
285
+
286
+ m, n = A.shape
287
+
288
+ b = np.atleast_1d(b)
289
+ if b.ndim != 1:
290
+ raise ValueError("`b` must have at most 1 dimension.")
291
+
292
+ if b.size != m:
293
+ raise ValueError("Inconsistent shapes between `A` and `b`.")
294
+
295
+ if isinstance(bounds, Bounds):
296
+ lb = bounds.lb
297
+ ub = bounds.ub
298
+ else:
299
+ lb, ub = prepare_bounds(bounds, n)
300
+
301
+ if lb.shape != (n,) and ub.shape != (n,):
302
+ raise ValueError("Bounds have wrong shape.")
303
+
304
+ if np.any(lb >= ub):
305
+ raise ValueError("Each lower bound must be strictly less than each "
306
+ "upper bound.")
307
+
308
+ if lsmr_maxiter is not None and lsmr_maxiter < 1:
309
+ raise ValueError("`lsmr_maxiter` must be None or positive integer.")
310
+
311
+ if not ((isinstance(lsmr_tol, float) and lsmr_tol > 0) or
312
+ lsmr_tol in ('auto', None)):
313
+ raise ValueError("`lsmr_tol` must be None, 'auto', or positive float.")
314
+
315
+ if lsq_solver == 'exact':
316
+ unbd_lsq = np.linalg.lstsq(A, b, rcond=-1)
317
+ elif lsq_solver == 'lsmr':
318
+ first_lsmr_tol = lsmr_tol # tol of first call to lsmr
319
+ if lsmr_tol is None or lsmr_tol == 'auto':
320
+ first_lsmr_tol = 1e-2 * tol # default if lsmr_tol not defined
321
+ unbd_lsq = lsmr(A, b, maxiter=lsmr_maxiter,
322
+ atol=first_lsmr_tol, btol=first_lsmr_tol)
323
+ x_lsq = unbd_lsq[0] # extract the solution from the least squares solver
324
+
325
+ if in_bounds(x_lsq, lb, ub):
326
+ r = A @ x_lsq - b
327
+ cost = 0.5 * np.dot(r, r)
328
+ termination_status = 3
329
+ termination_message = TERMINATION_MESSAGES[termination_status]
330
+ g = compute_grad(A, r)
331
+ g_norm = norm(g, ord=np.inf)
332
+
333
+ if verbose > 0:
334
+ print(termination_message)
335
+ print(f"Final cost {cost:.4e}, first-order optimality {g_norm:.2e}")
336
+
337
+ return OptimizeResult(
338
+ x=x_lsq, fun=r, cost=cost, optimality=g_norm,
339
+ active_mask=np.zeros(n), unbounded_sol=unbd_lsq,
340
+ nit=0, status=termination_status,
341
+ message=termination_message, success=True)
342
+
343
+ if method == 'trf':
344
+ res = trf_linear(A, b, x_lsq, lb, ub, tol, lsq_solver, lsmr_tol,
345
+ max_iter, verbose, lsmr_maxiter=lsmr_maxiter)
346
+ elif method == 'bvls':
347
+ res = bvls(A, b, x_lsq, lb, ub, tol, max_iter, verbose)
348
+
349
+ res.unbounded_sol = unbd_lsq
350
+ res.message = TERMINATION_MESSAGES[res.status]
351
+ res.success = res.status > 0
352
+
353
+ if verbose > 0:
354
+ print(res.message)
355
+ print(
356
+ f"Number of iterations {res.nit}, initial cost {res.initial_cost:.4e}, "
357
+ f"final cost {res.cost:.4e}, first-order optimality {res.optimality:.2e}."
358
+ )
359
+
360
+ del res.initial_cost
361
+
362
+ return res
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/trf.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trust Region Reflective algorithm for least-squares optimization.
2
+
3
+ The algorithm is based on ideas from paper [STIR]_. The main idea is to
4
+ account for the presence of the bounds by appropriate scaling of the variables (or,
5
+ equivalently, changing a trust-region shape). Let's introduce a vector v:
6
+
7
+ | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf
8
+ v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf
9
+ | 1, otherwise
10
+
11
+ where g is the gradient of a cost function and lb, ub are the bounds. Its
12
+ components are distances to the bounds at which the anti-gradient points (if
13
+ this distance is finite). Define a scaling matrix D = diag(v**0.5).
14
+ First-order optimality conditions can be stated as
15
+
16
+ D^2 g(x) = 0.
17
+
18
+ Meaning that components of the gradient should be zero for strictly interior
19
+ variables, and components must point inside the feasible region for variables
20
+ on the bound.
21
+
22
+ Now consider this system of equations as a new optimization problem. If the
23
+ point x is strictly interior (not on the bound), then the left-hand side is
24
+ differentiable and the Newton step for it satisfies
25
+
26
+ (D^2 H + diag(g) Jv) p = -D^2 g
27
+
28
+ where H is the Hessian matrix (or its J^T J approximation in least squares),
29
+ Jv is the Jacobian matrix of v with components -1, 1 or 0, such that all
30
+ elements of matrix C = diag(g) Jv are non-negative. Introduce the change
31
+ of the variables x = D x_h (_h would be "hat" in LaTeX). In the new variables,
32
+ we have a Newton step satisfying
33
+
34
+ B_h p_h = -g_h,
35
+
36
+ where B_h = D H D + C, g_h = D g. In least squares B_h = J_h^T J_h, where
37
+ J_h = J D. Note that J_h and g_h are proper Jacobian and gradient with respect
38
+ to "hat" variables. To guarantee global convergence we formulate a
39
+ trust-region problem based on the Newton step in the new variables:
40
+
41
+ 0.5 * p_h^T B_h p + g_h^T p_h -> min, ||p_h|| <= Delta
42
+
43
+ In the original space B = H + D^{-1} C D^{-1}, and the equivalent trust-region
44
+ problem is
45
+
46
+ 0.5 * p^T B p + g^T p -> min, ||D^{-1} p|| <= Delta
47
+
48
+ Here, the meaning of the matrix D becomes more clear: it alters the shape
49
+ of a trust-region, such that large steps towards the bounds are not allowed.
50
+ In the implementation, the trust-region problem is solved in "hat" space,
51
+ but handling of the bounds is done in the original space (see below and read
52
+ the code).
53
+
54
+ The introduction of the matrix D doesn't allow to ignore bounds, the algorithm
55
+ must keep iterates strictly feasible (to satisfy aforementioned
56
+ differentiability), the parameter theta controls step back from the boundary
57
+ (see the code for details).
58
+
59
+ The algorithm does another important trick. If the trust-region solution
60
+ doesn't fit into the bounds, then a reflected (from a firstly encountered
61
+ bound) search direction is considered. For motivation and analysis refer to
62
+ [STIR]_ paper (and other papers of the authors). In practice, it doesn't need
63
+ a lot of justifications, the algorithm simply chooses the best step among
64
+ three: a constrained trust-region step, a reflected step and a constrained
65
+ Cauchy step (a minimizer along -g_h in "hat" space, or -D^2 g in the original
66
+ space).
67
+
68
+ Another feature is that a trust-region radius control strategy is modified to
69
+ account for appearance of the diagonal C matrix (called diag_h in the code).
70
+
71
+ Note that all described peculiarities are completely gone as we consider
72
+ problems without bounds (the algorithm becomes a standard trust-region type
73
+ algorithm very similar to ones implemented in MINPACK).
74
+
75
+ The implementation supports two methods of solving the trust-region problem.
76
+ The first, called 'exact', applies SVD on Jacobian and then solves the problem
77
+ very accurately using the algorithm described in [JJMore]_. It is not
78
+ applicable to large problem. The second, called 'lsmr', uses the 2-D subspace
79
+ approach (sometimes called "indefinite dogleg"), where the problem is solved
80
+ in a subspace spanned by the gradient and the approximate Gauss-Newton step
81
+ found by ``scipy.sparse.linalg.lsmr``. A 2-D trust-region problem is
82
+ reformulated as a 4th order algebraic equation and solved very accurately by
83
+ ``numpy.roots``. The subspace approach allows to solve very large problems
84
+ (up to couple of millions of residuals on a regular PC), provided the Jacobian
85
+ matrix is sufficiently sparse.
86
+
87
+ References
88
+ ----------
89
+ .. [STIR] Branch, M.A., T.F. Coleman, and Y. Li, "A Subspace, Interior,
90
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
91
+ Minimization Problems," SIAM Journal on Scientific Computing,
92
+ Vol. 21, Number 1, pp 1-23, 1999.
93
+ .. [JJMore] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
94
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
95
+ """
96
+ import numpy as np
97
+ from numpy.linalg import norm
98
+ from scipy.linalg import svd, qr
99
+ from scipy.sparse.linalg import lsmr
100
+ from scipy.optimize import OptimizeResult
101
+
102
+ from .common import (
103
+ step_size_to_bound, find_active_constraints, in_bounds,
104
+ make_strictly_feasible, intersect_trust_region, solve_lsq_trust_region,
105
+ solve_trust_region_2d, minimize_quadratic_1d, build_quadratic_1d,
106
+ evaluate_quadratic, right_multiplied_operator, regularized_lsq_operator,
107
+ CL_scaling_vector, compute_grad, compute_jac_scale, check_termination,
108
+ update_tr_radius, scale_for_robust_loss_function, print_header_nonlinear,
109
+ print_iteration_nonlinear)
110
+
111
+
112
+ def trf(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
113
+ loss_function, tr_solver, tr_options, verbose):
114
+ # For efficiency, it makes sense to run the simplified version of the
115
+ # algorithm when no bounds are imposed. We decided to write the two
116
+ # separate functions. It violates the DRY principle, but the individual
117
+ # functions are kept the most readable.
118
+ if np.all(lb == -np.inf) and np.all(ub == np.inf):
119
+ return trf_no_bounds(
120
+ fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev, x_scale,
121
+ loss_function, tr_solver, tr_options, verbose)
122
+ else:
123
+ return trf_bounds(
124
+ fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
125
+ loss_function, tr_solver, tr_options, verbose)
126
+
127
+
128
+ def select_step(x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta):
129
+ """Select the best step according to Trust Region Reflective algorithm."""
130
+ if in_bounds(x + p, lb, ub):
131
+ p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h)
132
+ return p, p_h, -p_value
133
+
134
+ p_stride, hits = step_size_to_bound(x, p, lb, ub)
135
+
136
+ # Compute the reflected direction.
137
+ r_h = np.copy(p_h)
138
+ r_h[hits.astype(bool)] *= -1
139
+ r = d * r_h
140
+
141
+ # Restrict trust-region step, such that it hits the bound.
142
+ p *= p_stride
143
+ p_h *= p_stride
144
+ x_on_bound = x + p
145
+
146
+ # Reflected direction will cross first either feasible region or trust
147
+ # region boundary.
148
+ _, to_tr = intersect_trust_region(p_h, r_h, Delta)
149
+ to_bound, _ = step_size_to_bound(x_on_bound, r, lb, ub)
150
+
151
+ # Find lower and upper bounds on a step size along the reflected
152
+ # direction, considering the strict feasibility requirement. There is no
153
+ # single correct way to do that, the chosen approach seems to work best
154
+ # on test problems.
155
+ r_stride = min(to_bound, to_tr)
156
+ if r_stride > 0:
157
+ r_stride_l = (1 - theta) * p_stride / r_stride
158
+ if r_stride == to_bound:
159
+ r_stride_u = theta * to_bound
160
+ else:
161
+ r_stride_u = to_tr
162
+ else:
163
+ r_stride_l = 0
164
+ r_stride_u = -1
165
+
166
+ # Check if reflection step is available.
167
+ if r_stride_l <= r_stride_u:
168
+ a, b, c = build_quadratic_1d(J_h, g_h, r_h, s0=p_h, diag=diag_h)
169
+ r_stride, r_value = minimize_quadratic_1d(
170
+ a, b, r_stride_l, r_stride_u, c=c)
171
+ r_h *= r_stride
172
+ r_h += p_h
173
+ r = r_h * d
174
+ else:
175
+ r_value = np.inf
176
+
177
+ # Now correct p_h to make it strictly interior.
178
+ p *= theta
179
+ p_h *= theta
180
+ p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h)
181
+
182
+ ag_h = -g_h
183
+ ag = d * ag_h
184
+
185
+ to_tr = Delta / norm(ag_h)
186
+ to_bound, _ = step_size_to_bound(x, ag, lb, ub)
187
+ if to_bound < to_tr:
188
+ ag_stride = theta * to_bound
189
+ else:
190
+ ag_stride = to_tr
191
+
192
+ a, b = build_quadratic_1d(J_h, g_h, ag_h, diag=diag_h)
193
+ ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride)
194
+ ag_h *= ag_stride
195
+ ag *= ag_stride
196
+
197
+ if p_value < r_value and p_value < ag_value:
198
+ return p, p_h, -p_value
199
+ elif r_value < p_value and r_value < ag_value:
200
+ return r, r_h, -r_value
201
+ else:
202
+ return ag, ag_h, -ag_value
203
+
204
+
205
+ def trf_bounds(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev,
206
+ x_scale, loss_function, tr_solver, tr_options, verbose):
207
+ x = x0.copy()
208
+
209
+ f = f0
210
+ f_true = f.copy()
211
+ nfev = 1
212
+
213
+ J = J0
214
+ njev = 1
215
+ m, n = J.shape
216
+
217
+ if loss_function is not None:
218
+ rho = loss_function(f)
219
+ cost = 0.5 * np.sum(rho[0])
220
+ J, f = scale_for_robust_loss_function(J, f, rho)
221
+ else:
222
+ cost = 0.5 * np.dot(f, f)
223
+
224
+ g = compute_grad(J, f)
225
+
226
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
227
+ if jac_scale:
228
+ scale, scale_inv = compute_jac_scale(J)
229
+ else:
230
+ scale, scale_inv = x_scale, 1 / x_scale
231
+
232
+ v, dv = CL_scaling_vector(x, g, lb, ub)
233
+ v[dv != 0] *= scale_inv[dv != 0]
234
+ Delta = norm(x0 * scale_inv / v**0.5)
235
+ if Delta == 0:
236
+ Delta = 1.0
237
+
238
+ g_norm = norm(g * v, ord=np.inf)
239
+
240
+ f_augmented = np.zeros(m + n)
241
+ if tr_solver == 'exact':
242
+ J_augmented = np.empty((m + n, n))
243
+ elif tr_solver == 'lsmr':
244
+ reg_term = 0.0
245
+ regularize = tr_options.pop('regularize', True)
246
+
247
+ if max_nfev is None:
248
+ max_nfev = x0.size * 100
249
+
250
+ alpha = 0.0 # "Levenberg-Marquardt" parameter
251
+
252
+ termination_status = None
253
+ iteration = 0
254
+ step_norm = None
255
+ actual_reduction = None
256
+
257
+ if verbose == 2:
258
+ print_header_nonlinear()
259
+
260
+ while True:
261
+ v, dv = CL_scaling_vector(x, g, lb, ub)
262
+
263
+ g_norm = norm(g * v, ord=np.inf)
264
+ if g_norm < gtol:
265
+ termination_status = 1
266
+
267
+ if verbose == 2:
268
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
269
+ step_norm, g_norm)
270
+
271
+ if termination_status is not None or nfev == max_nfev:
272
+ break
273
+
274
+ # Now compute variables in "hat" space. Here, we also account for
275
+ # scaling introduced by `x_scale` parameter. This part is a bit tricky,
276
+ # you have to write down the formulas and see how the trust-region
277
+ # problem is formulated when the two types of scaling are applied.
278
+ # The idea is that first we apply `x_scale` and then apply Coleman-Li
279
+ # approach in the new variables.
280
+
281
+ # v is recomputed in the variables after applying `x_scale`, note that
282
+ # components which were identically 1 not affected.
283
+ v[dv != 0] *= scale_inv[dv != 0]
284
+
285
+ # Here, we apply two types of scaling.
286
+ d = v**0.5 * scale
287
+
288
+ # C = diag(g * scale) Jv
289
+ diag_h = g * dv * scale
290
+
291
+ # After all this has been done, we continue normally.
292
+
293
+ # "hat" gradient.
294
+ g_h = d * g
295
+
296
+ f_augmented[:m] = f
297
+ if tr_solver == 'exact':
298
+ J_augmented[:m] = J * d
299
+ J_h = J_augmented[:m] # Memory view.
300
+ J_augmented[m:] = np.diag(diag_h**0.5)
301
+ U, s, V = svd(J_augmented, full_matrices=False)
302
+ V = V.T
303
+ uf = U.T.dot(f_augmented)
304
+ elif tr_solver == 'lsmr':
305
+ J_h = right_multiplied_operator(J, d)
306
+
307
+ if regularize:
308
+ a, b = build_quadratic_1d(J_h, g_h, -g_h, diag=diag_h)
309
+ to_tr = Delta / norm(g_h)
310
+ ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1]
311
+ reg_term = -ag_value / Delta**2
312
+
313
+ lsmr_op = regularized_lsq_operator(J_h, (diag_h + reg_term)**0.5)
314
+ gn_h = lsmr(lsmr_op, f_augmented, **tr_options)[0]
315
+ S = np.vstack((g_h, gn_h)).T
316
+ S, _ = qr(S, mode='economic')
317
+ JS = J_h.dot(S) # LinearOperator does dot too.
318
+ B_S = np.dot(JS.T, JS) + np.dot(S.T * diag_h, S)
319
+ g_S = S.T.dot(g_h)
320
+
321
+ # theta controls step back step ratio from the bounds.
322
+ theta = max(0.995, 1 - g_norm)
323
+
324
+ actual_reduction = -1
325
+ while actual_reduction <= 0 and nfev < max_nfev:
326
+ if tr_solver == 'exact':
327
+ p_h, alpha, n_iter = solve_lsq_trust_region(
328
+ n, m, uf, s, V, Delta, initial_alpha=alpha)
329
+ elif tr_solver == 'lsmr':
330
+ p_S, _ = solve_trust_region_2d(B_S, g_S, Delta)
331
+ p_h = S.dot(p_S)
332
+
333
+ p = d * p_h # Trust-region solution in the original space.
334
+ step, step_h, predicted_reduction = select_step(
335
+ x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta)
336
+
337
+ x_new = make_strictly_feasible(x + step, lb, ub, rstep=0)
338
+ f_new = fun(x_new)
339
+ nfev += 1
340
+
341
+ step_h_norm = norm(step_h)
342
+
343
+ if not np.all(np.isfinite(f_new)):
344
+ Delta = 0.25 * step_h_norm
345
+ continue
346
+
347
+ # Usual trust-region step quality estimation.
348
+ if loss_function is not None:
349
+ cost_new = loss_function(f_new, cost_only=True)
350
+ else:
351
+ cost_new = 0.5 * np.dot(f_new, f_new)
352
+ actual_reduction = cost - cost_new
353
+ Delta_new, ratio = update_tr_radius(
354
+ Delta, actual_reduction, predicted_reduction,
355
+ step_h_norm, step_h_norm > 0.95 * Delta)
356
+
357
+ step_norm = norm(step)
358
+ termination_status = check_termination(
359
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
360
+ if termination_status is not None:
361
+ break
362
+
363
+ alpha *= Delta / Delta_new
364
+ Delta = Delta_new
365
+
366
+ if actual_reduction > 0:
367
+ x = x_new
368
+
369
+ f = f_new
370
+ f_true = f.copy()
371
+
372
+ cost = cost_new
373
+
374
+ J = jac(x, f)
375
+ njev += 1
376
+
377
+ if loss_function is not None:
378
+ rho = loss_function(f)
379
+ J, f = scale_for_robust_loss_function(J, f, rho)
380
+
381
+ g = compute_grad(J, f)
382
+
383
+ if jac_scale:
384
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
385
+ else:
386
+ step_norm = 0
387
+ actual_reduction = 0
388
+
389
+ iteration += 1
390
+
391
+ if termination_status is None:
392
+ termination_status = 0
393
+
394
+ active_mask = find_active_constraints(x, lb, ub, rtol=xtol)
395
+ return OptimizeResult(
396
+ x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm,
397
+ active_mask=active_mask, nfev=nfev, njev=njev,
398
+ status=termination_status)
399
+
400
+
401
+ def trf_no_bounds(fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev,
402
+ x_scale, loss_function, tr_solver, tr_options, verbose):
403
+ x = x0.copy()
404
+
405
+ f = f0
406
+ f_true = f.copy()
407
+ nfev = 1
408
+
409
+ J = J0
410
+ njev = 1
411
+ m, n = J.shape
412
+
413
+ if loss_function is not None:
414
+ rho = loss_function(f)
415
+ cost = 0.5 * np.sum(rho[0])
416
+ J, f = scale_for_robust_loss_function(J, f, rho)
417
+ else:
418
+ cost = 0.5 * np.dot(f, f)
419
+
420
+ g = compute_grad(J, f)
421
+
422
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
423
+ if jac_scale:
424
+ scale, scale_inv = compute_jac_scale(J)
425
+ else:
426
+ scale, scale_inv = x_scale, 1 / x_scale
427
+
428
+ Delta = norm(x0 * scale_inv)
429
+ if Delta == 0:
430
+ Delta = 1.0
431
+
432
+ if tr_solver == 'lsmr':
433
+ reg_term = 0
434
+ damp = tr_options.pop('damp', 0.0)
435
+ regularize = tr_options.pop('regularize', True)
436
+
437
+ if max_nfev is None:
438
+ max_nfev = x0.size * 100
439
+
440
+ alpha = 0.0 # "Levenberg-Marquardt" parameter
441
+
442
+ termination_status = None
443
+ iteration = 0
444
+ step_norm = None
445
+ actual_reduction = None
446
+
447
+ if verbose == 2:
448
+ print_header_nonlinear()
449
+
450
+ while True:
451
+ g_norm = norm(g, ord=np.inf)
452
+ if g_norm < gtol:
453
+ termination_status = 1
454
+
455
+ if verbose == 2:
456
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
457
+ step_norm, g_norm)
458
+
459
+ if termination_status is not None or nfev == max_nfev:
460
+ break
461
+
462
+ d = scale
463
+ g_h = d * g
464
+
465
+ if tr_solver == 'exact':
466
+ J_h = J * d
467
+ U, s, V = svd(J_h, full_matrices=False)
468
+ V = V.T
469
+ uf = U.T.dot(f)
470
+ elif tr_solver == 'lsmr':
471
+ J_h = right_multiplied_operator(J, d)
472
+
473
+ if regularize:
474
+ a, b = build_quadratic_1d(J_h, g_h, -g_h)
475
+ to_tr = Delta / norm(g_h)
476
+ ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1]
477
+ reg_term = -ag_value / Delta**2
478
+
479
+ damp_full = (damp**2 + reg_term)**0.5
480
+ gn_h = lsmr(J_h, f, damp=damp_full, **tr_options)[0]
481
+ S = np.vstack((g_h, gn_h)).T
482
+ S, _ = qr(S, mode='economic')
483
+ JS = J_h.dot(S)
484
+ B_S = np.dot(JS.T, JS)
485
+ g_S = S.T.dot(g_h)
486
+
487
+ actual_reduction = -1
488
+ while actual_reduction <= 0 and nfev < max_nfev:
489
+ if tr_solver == 'exact':
490
+ step_h, alpha, n_iter = solve_lsq_trust_region(
491
+ n, m, uf, s, V, Delta, initial_alpha=alpha)
492
+ elif tr_solver == 'lsmr':
493
+ p_S, _ = solve_trust_region_2d(B_S, g_S, Delta)
494
+ step_h = S.dot(p_S)
495
+
496
+ predicted_reduction = -evaluate_quadratic(J_h, g_h, step_h)
497
+ step = d * step_h
498
+ x_new = x + step
499
+ f_new = fun(x_new)
500
+ nfev += 1
501
+
502
+ step_h_norm = norm(step_h)
503
+
504
+ if not np.all(np.isfinite(f_new)):
505
+ Delta = 0.25 * step_h_norm
506
+ continue
507
+
508
+ # Usual trust-region step quality estimation.
509
+ if loss_function is not None:
510
+ cost_new = loss_function(f_new, cost_only=True)
511
+ else:
512
+ cost_new = 0.5 * np.dot(f_new, f_new)
513
+ actual_reduction = cost - cost_new
514
+
515
+ Delta_new, ratio = update_tr_radius(
516
+ Delta, actual_reduction, predicted_reduction,
517
+ step_h_norm, step_h_norm > 0.95 * Delta)
518
+
519
+ step_norm = norm(step)
520
+ termination_status = check_termination(
521
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
522
+ if termination_status is not None:
523
+ break
524
+
525
+ alpha *= Delta / Delta_new
526
+ Delta = Delta_new
527
+
528
+ if actual_reduction > 0:
529
+ x = x_new
530
+
531
+ f = f_new
532
+ f_true = f.copy()
533
+
534
+ cost = cost_new
535
+
536
+ J = jac(x, f)
537
+ njev += 1
538
+
539
+ if loss_function is not None:
540
+ rho = loss_function(f)
541
+ J, f = scale_for_robust_loss_function(J, f, rho)
542
+
543
+ g = compute_grad(J, f)
544
+
545
+ if jac_scale:
546
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
547
+ else:
548
+ step_norm = 0
549
+ actual_reduction = 0
550
+
551
+ iteration += 1
552
+
553
+ if termination_status is None:
554
+ termination_status = 0
555
+
556
+ active_mask = np.zeros_like(x)
557
+ return OptimizeResult(
558
+ x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm,
559
+ active_mask=active_mask, nfev=nfev, njev=njev,
560
+ status=termination_status)
parrot/lib/python3.10/site-packages/scipy/optimize/_lsq/trf_linear.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The adaptation of Trust Region Reflective algorithm for a linear
2
+ least-squares problem."""
3
+ import numpy as np
4
+ from numpy.linalg import norm
5
+ from scipy.linalg import qr, solve_triangular
6
+ from scipy.sparse.linalg import lsmr
7
+ from scipy.optimize import OptimizeResult
8
+
9
+ from .givens_elimination import givens_elimination
10
+ from .common import (
11
+ EPS, step_size_to_bound, find_active_constraints, in_bounds,
12
+ make_strictly_feasible, build_quadratic_1d, evaluate_quadratic,
13
+ minimize_quadratic_1d, CL_scaling_vector, reflective_transformation,
14
+ print_header_linear, print_iteration_linear, compute_grad,
15
+ regularized_lsq_operator, right_multiplied_operator)
16
+
17
+
18
+ def regularized_lsq_with_qr(m, n, R, QTb, perm, diag, copy_R=True):
19
+ """Solve regularized least squares using information from QR-decomposition.
20
+
21
+ The initial problem is to solve the following system in a least-squares
22
+ sense::
23
+
24
+ A x = b
25
+ D x = 0
26
+
27
+ where D is diagonal matrix. The method is based on QR decomposition
28
+ of the form A P = Q R, where P is a column permutation matrix, Q is an
29
+ orthogonal matrix and R is an upper triangular matrix.
30
+
31
+ Parameters
32
+ ----------
33
+ m, n : int
34
+ Initial shape of A.
35
+ R : ndarray, shape (n, n)
36
+ Upper triangular matrix from QR decomposition of A.
37
+ QTb : ndarray, shape (n,)
38
+ First n components of Q^T b.
39
+ perm : ndarray, shape (n,)
40
+ Array defining column permutation of A, such that ith column of
41
+ P is perm[i]-th column of identity matrix.
42
+ diag : ndarray, shape (n,)
43
+ Array containing diagonal elements of D.
44
+
45
+ Returns
46
+ -------
47
+ x : ndarray, shape (n,)
48
+ Found least-squares solution.
49
+ """
50
+ if copy_R:
51
+ R = R.copy()
52
+ v = QTb.copy()
53
+
54
+ givens_elimination(R, v, diag[perm])
55
+
56
+ abs_diag_R = np.abs(np.diag(R))
57
+ threshold = EPS * max(m, n) * np.max(abs_diag_R)
58
+ nns, = np.nonzero(abs_diag_R > threshold)
59
+
60
+ R = R[np.ix_(nns, nns)]
61
+ v = v[nns]
62
+
63
+ x = np.zeros(n)
64
+ x[perm[nns]] = solve_triangular(R, v)
65
+
66
+ return x
67
+
68
+
69
+ def backtracking(A, g, x, p, theta, p_dot_g, lb, ub):
70
+ """Find an appropriate step size using backtracking line search."""
71
+ alpha = 1
72
+ while True:
73
+ x_new, _ = reflective_transformation(x + alpha * p, lb, ub)
74
+ step = x_new - x
75
+ cost_change = -evaluate_quadratic(A, g, step)
76
+ if cost_change > -0.1 * alpha * p_dot_g:
77
+ break
78
+ alpha *= 0.5
79
+
80
+ active = find_active_constraints(x_new, lb, ub)
81
+ if np.any(active != 0):
82
+ x_new, _ = reflective_transformation(x + theta * alpha * p, lb, ub)
83
+ x_new = make_strictly_feasible(x_new, lb, ub, rstep=0)
84
+ step = x_new - x
85
+ cost_change = -evaluate_quadratic(A, g, step)
86
+
87
+ return x, step, cost_change
88
+
89
+
90
+ def select_step(x, A_h, g_h, c_h, p, p_h, d, lb, ub, theta):
91
+ """Select the best step according to Trust Region Reflective algorithm."""
92
+ if in_bounds(x + p, lb, ub):
93
+ return p
94
+
95
+ p_stride, hits = step_size_to_bound(x, p, lb, ub)
96
+ r_h = np.copy(p_h)
97
+ r_h[hits.astype(bool)] *= -1
98
+ r = d * r_h
99
+
100
+ # Restrict step, such that it hits the bound.
101
+ p *= p_stride
102
+ p_h *= p_stride
103
+ x_on_bound = x + p
104
+
105
+ # Find the step size along reflected direction.
106
+ r_stride_u, _ = step_size_to_bound(x_on_bound, r, lb, ub)
107
+
108
+ # Stay interior.
109
+ r_stride_l = (1 - theta) * r_stride_u
110
+ r_stride_u *= theta
111
+
112
+ if r_stride_u > 0:
113
+ a, b, c = build_quadratic_1d(A_h, g_h, r_h, s0=p_h, diag=c_h)
114
+ r_stride, r_value = minimize_quadratic_1d(
115
+ a, b, r_stride_l, r_stride_u, c=c)
116
+ r_h = p_h + r_h * r_stride
117
+ r = d * r_h
118
+ else:
119
+ r_value = np.inf
120
+
121
+ # Now correct p_h to make it strictly interior.
122
+ p_h *= theta
123
+ p *= theta
124
+ p_value = evaluate_quadratic(A_h, g_h, p_h, diag=c_h)
125
+
126
+ ag_h = -g_h
127
+ ag = d * ag_h
128
+ ag_stride_u, _ = step_size_to_bound(x, ag, lb, ub)
129
+ ag_stride_u *= theta
130
+ a, b = build_quadratic_1d(A_h, g_h, ag_h, diag=c_h)
131
+ ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride_u)
132
+ ag *= ag_stride
133
+
134
+ if p_value < r_value and p_value < ag_value:
135
+ return p
136
+ elif r_value < p_value and r_value < ag_value:
137
+ return r
138
+ else:
139
+ return ag
140
+
141
+
142
+ def trf_linear(A, b, x_lsq, lb, ub, tol, lsq_solver, lsmr_tol,
143
+ max_iter, verbose, *, lsmr_maxiter=None):
144
+ m, n = A.shape
145
+ x, _ = reflective_transformation(x_lsq, lb, ub)
146
+ x = make_strictly_feasible(x, lb, ub, rstep=0.1)
147
+
148
+ if lsq_solver == 'exact':
149
+ QT, R, perm = qr(A, mode='economic', pivoting=True)
150
+ QT = QT.T
151
+
152
+ if m < n:
153
+ R = np.vstack((R, np.zeros((n - m, n))))
154
+
155
+ QTr = np.zeros(n)
156
+ k = min(m, n)
157
+ elif lsq_solver == 'lsmr':
158
+ r_aug = np.zeros(m + n)
159
+ auto_lsmr_tol = False
160
+ if lsmr_tol is None:
161
+ lsmr_tol = 1e-2 * tol
162
+ elif lsmr_tol == 'auto':
163
+ auto_lsmr_tol = True
164
+
165
+ r = A.dot(x) - b
166
+ g = compute_grad(A, r)
167
+ cost = 0.5 * np.dot(r, r)
168
+ initial_cost = cost
169
+
170
+ termination_status = None
171
+ step_norm = None
172
+ cost_change = None
173
+
174
+ if max_iter is None:
175
+ max_iter = 100
176
+
177
+ if verbose == 2:
178
+ print_header_linear()
179
+
180
+ for iteration in range(max_iter):
181
+ v, dv = CL_scaling_vector(x, g, lb, ub)
182
+ g_scaled = g * v
183
+ g_norm = norm(g_scaled, ord=np.inf)
184
+ if g_norm < tol:
185
+ termination_status = 1
186
+
187
+ if verbose == 2:
188
+ print_iteration_linear(iteration, cost, cost_change,
189
+ step_norm, g_norm)
190
+
191
+ if termination_status is not None:
192
+ break
193
+
194
+ diag_h = g * dv
195
+ diag_root_h = diag_h ** 0.5
196
+ d = v ** 0.5
197
+ g_h = d * g
198
+
199
+ A_h = right_multiplied_operator(A, d)
200
+ if lsq_solver == 'exact':
201
+ QTr[:k] = QT.dot(r)
202
+ p_h = -regularized_lsq_with_qr(m, n, R * d[perm], QTr, perm,
203
+ diag_root_h, copy_R=False)
204
+ elif lsq_solver == 'lsmr':
205
+ lsmr_op = regularized_lsq_operator(A_h, diag_root_h)
206
+ r_aug[:m] = r
207
+ if auto_lsmr_tol:
208
+ eta = 1e-2 * min(0.5, g_norm)
209
+ lsmr_tol = max(EPS, min(0.1, eta * g_norm))
210
+ p_h = -lsmr(lsmr_op, r_aug, maxiter=lsmr_maxiter,
211
+ atol=lsmr_tol, btol=lsmr_tol)[0]
212
+
213
+ p = d * p_h
214
+
215
+ p_dot_g = np.dot(p, g)
216
+ if p_dot_g > 0:
217
+ termination_status = -1
218
+
219
+ theta = 1 - min(0.005, g_norm)
220
+ step = select_step(x, A_h, g_h, diag_h, p, p_h, d, lb, ub, theta)
221
+ cost_change = -evaluate_quadratic(A, g, step)
222
+
223
+ # Perhaps almost never executed, the idea is that `p` is descent
224
+ # direction thus we must find acceptable cost decrease using simple
225
+ # "backtracking", otherwise the algorithm's logic would break.
226
+ if cost_change < 0:
227
+ x, step, cost_change = backtracking(
228
+ A, g, x, p, theta, p_dot_g, lb, ub)
229
+ else:
230
+ x = make_strictly_feasible(x + step, lb, ub, rstep=0)
231
+
232
+ step_norm = norm(step)
233
+ r = A.dot(x) - b
234
+ g = compute_grad(A, r)
235
+
236
+ if cost_change < tol * cost:
237
+ termination_status = 2
238
+
239
+ cost = 0.5 * np.dot(r, r)
240
+
241
+ if termination_status is None:
242
+ termination_status = 0
243
+
244
+ active_mask = find_active_constraints(x, lb, ub, rtol=tol)
245
+
246
+ return OptimizeResult(
247
+ x=x, fun=r, cost=cost, optimality=g_norm, active_mask=active_mask,
248
+ nit=iteration + 1, status=termination_status,
249
+ initial_cost=initial_cost)
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (362 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Byrd-Omojokun Trust-Region SQP method."""
2
+
3
+ from scipy.sparse import eye as speye
4
+ from .projections import projections
5
+ from .qp_subproblem import modified_dogleg, projected_cg, box_intersections
6
+ import numpy as np
7
+ from numpy.linalg import norm
8
+
9
+ __all__ = ['equality_constrained_sqp']
10
+
11
+
12
+ def default_scaling(x):
13
+ n, = np.shape(x)
14
+ return speye(n)
15
+
16
+
17
+ def equality_constrained_sqp(fun_and_constr, grad_and_jac, lagr_hess,
18
+ x0, fun0, grad0, constr0,
19
+ jac0, stop_criteria,
20
+ state,
21
+ initial_penalty,
22
+ initial_trust_radius,
23
+ factorization_method,
24
+ trust_lb=None,
25
+ trust_ub=None,
26
+ scaling=default_scaling):
27
+ """Solve nonlinear equality-constrained problem using trust-region SQP.
28
+
29
+ Solve optimization problem:
30
+
31
+ minimize fun(x)
32
+ subject to: constr(x) = 0
33
+
34
+ using Byrd-Omojokun Trust-Region SQP method described in [1]_. Several
35
+ implementation details are based on [2]_ and [3]_, p. 549.
36
+
37
+ References
38
+ ----------
39
+ .. [1] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. "On the
40
+ implementation of an algorithm for large-scale equality
41
+ constrained optimization." SIAM Journal on
42
+ Optimization 8.3 (1998): 682-706.
43
+ .. [2] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal.
44
+ "An interior point algorithm for large-scale nonlinear
45
+ programming." SIAM Journal on Optimization 9.4 (1999): 877-900.
46
+ .. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
47
+ Second Edition (2006).
48
+ """
49
+ PENALTY_FACTOR = 0.3 # Rho from formula (3.51), reference [2]_, p.891.
50
+ LARGE_REDUCTION_RATIO = 0.9
51
+ INTERMEDIARY_REDUCTION_RATIO = 0.3
52
+ SUFFICIENT_REDUCTION_RATIO = 1e-8 # Eta from reference [2]_, p.892.
53
+ TRUST_ENLARGEMENT_FACTOR_L = 7.0
54
+ TRUST_ENLARGEMENT_FACTOR_S = 2.0
55
+ MAX_TRUST_REDUCTION = 0.5
56
+ MIN_TRUST_REDUCTION = 0.1
57
+ SOC_THRESHOLD = 0.1
58
+ TR_FACTOR = 0.8 # Zeta from formula (3.21), reference [2]_, p.885.
59
+ BOX_FACTOR = 0.5
60
+
61
+ n, = np.shape(x0) # Number of parameters
62
+
63
+ # Set default lower and upper bounds.
64
+ if trust_lb is None:
65
+ trust_lb = np.full(n, -np.inf)
66
+ if trust_ub is None:
67
+ trust_ub = np.full(n, np.inf)
68
+
69
+ # Initial values
70
+ x = np.copy(x0)
71
+ trust_radius = initial_trust_radius
72
+ penalty = initial_penalty
73
+ # Compute Values
74
+ f = fun0
75
+ c = grad0
76
+ b = constr0
77
+ A = jac0
78
+ S = scaling(x)
79
+ # Get projections
80
+ try:
81
+ Z, LS, Y = projections(A, factorization_method)
82
+ except ValueError as e:
83
+ if str(e) == "expected square matrix":
84
+ # can be the case if there are more equality
85
+ # constraints than independent variables
86
+ raise ValueError(
87
+ "The 'expected square matrix' error can occur if there are"
88
+ " more equality constraints than independent variables."
89
+ " Consider how your constraints are set up, or use"
90
+ " factorization_method='SVDFactorization'."
91
+ ) from e
92
+ else:
93
+ raise e
94
+
95
+ # Compute least-square lagrange multipliers
96
+ v = -LS.dot(c)
97
+ # Compute Hessian
98
+ H = lagr_hess(x, v)
99
+
100
+ # Update state parameters
101
+ optimality = norm(c + A.T.dot(v), np.inf)
102
+ constr_violation = norm(b, np.inf) if len(b) > 0 else 0
103
+ cg_info = {'niter': 0, 'stop_cond': 0,
104
+ 'hits_boundary': False}
105
+
106
+ last_iteration_failed = False
107
+ while not stop_criteria(state, x, last_iteration_failed,
108
+ optimality, constr_violation,
109
+ trust_radius, penalty, cg_info):
110
+ # Normal Step - `dn`
111
+ # minimize 1/2*||A dn + b||^2
112
+ # subject to:
113
+ # ||dn|| <= TR_FACTOR * trust_radius
114
+ # BOX_FACTOR * lb <= dn <= BOX_FACTOR * ub.
115
+ dn = modified_dogleg(A, Y, b,
116
+ TR_FACTOR*trust_radius,
117
+ BOX_FACTOR*trust_lb,
118
+ BOX_FACTOR*trust_ub)
119
+
120
+ # Tangential Step - `dt`
121
+ # Solve the QP problem:
122
+ # minimize 1/2 dt.T H dt + dt.T (H dn + c)
123
+ # subject to:
124
+ # A dt = 0
125
+ # ||dt|| <= sqrt(trust_radius**2 - ||dn||**2)
126
+ # lb - dn <= dt <= ub - dn
127
+ c_t = H.dot(dn) + c
128
+ b_t = np.zeros_like(b)
129
+ trust_radius_t = np.sqrt(trust_radius**2 - np.linalg.norm(dn)**2)
130
+ lb_t = trust_lb - dn
131
+ ub_t = trust_ub - dn
132
+ dt, cg_info = projected_cg(H, c_t, Z, Y, b_t,
133
+ trust_radius_t,
134
+ lb_t, ub_t)
135
+
136
+ # Compute update (normal + tangential steps).
137
+ d = dn + dt
138
+
139
+ # Compute second order model: 1/2 d H d + c.T d + f.
140
+ quadratic_model = 1/2*(H.dot(d)).dot(d) + c.T.dot(d)
141
+ # Compute linearized constraint: l = A d + b.
142
+ linearized_constr = A.dot(d)+b
143
+ # Compute new penalty parameter according to formula (3.52),
144
+ # reference [2]_, p.891.
145
+ vpred = norm(b) - norm(linearized_constr)
146
+ # Guarantee `vpred` always positive,
147
+ # regardless of roundoff errors.
148
+ vpred = max(1e-16, vpred)
149
+ previous_penalty = penalty
150
+ if quadratic_model > 0:
151
+ new_penalty = quadratic_model / ((1-PENALTY_FACTOR)*vpred)
152
+ penalty = max(penalty, new_penalty)
153
+ # Compute predicted reduction according to formula (3.52),
154
+ # reference [2]_, p.891.
155
+ predicted_reduction = -quadratic_model + penalty*vpred
156
+
157
+ # Compute merit function at current point
158
+ merit_function = f + penalty*norm(b)
159
+ # Evaluate function and constraints at trial point
160
+ x_next = x + S.dot(d)
161
+ f_next, b_next = fun_and_constr(x_next)
162
+ # Compute merit function at trial point
163
+ merit_function_next = f_next + penalty*norm(b_next)
164
+ # Compute actual reduction according to formula (3.54),
165
+ # reference [2]_, p.892.
166
+ actual_reduction = merit_function - merit_function_next
167
+ # Compute reduction ratio
168
+ reduction_ratio = actual_reduction / predicted_reduction
169
+
170
+ # Second order correction (SOC), reference [2]_, p.892.
171
+ if reduction_ratio < SUFFICIENT_REDUCTION_RATIO and \
172
+ norm(dn) <= SOC_THRESHOLD * norm(dt):
173
+ # Compute second order correction
174
+ y = -Y.dot(b_next)
175
+ # Make sure increment is inside box constraints
176
+ _, t, intersect = box_intersections(d, y, trust_lb, trust_ub)
177
+ # Compute tentative point
178
+ x_soc = x + S.dot(d + t*y)
179
+ f_soc, b_soc = fun_and_constr(x_soc)
180
+ # Recompute actual reduction
181
+ merit_function_soc = f_soc + penalty*norm(b_soc)
182
+ actual_reduction_soc = merit_function - merit_function_soc
183
+ # Recompute reduction ratio
184
+ reduction_ratio_soc = actual_reduction_soc / predicted_reduction
185
+ if intersect and reduction_ratio_soc >= SUFFICIENT_REDUCTION_RATIO:
186
+ x_next = x_soc
187
+ f_next = f_soc
188
+ b_next = b_soc
189
+ reduction_ratio = reduction_ratio_soc
190
+
191
+ # Readjust trust region step, formula (3.55), reference [2]_, p.892.
192
+ if reduction_ratio >= LARGE_REDUCTION_RATIO:
193
+ trust_radius = max(TRUST_ENLARGEMENT_FACTOR_L * norm(d),
194
+ trust_radius)
195
+ elif reduction_ratio >= INTERMEDIARY_REDUCTION_RATIO:
196
+ trust_radius = max(TRUST_ENLARGEMENT_FACTOR_S * norm(d),
197
+ trust_radius)
198
+ # Reduce trust region step, according to reference [3]_, p.696.
199
+ elif reduction_ratio < SUFFICIENT_REDUCTION_RATIO:
200
+ trust_reduction = ((1-SUFFICIENT_REDUCTION_RATIO) /
201
+ (1-reduction_ratio))
202
+ new_trust_radius = trust_reduction * norm(d)
203
+ if new_trust_radius >= MAX_TRUST_REDUCTION * trust_radius:
204
+ trust_radius *= MAX_TRUST_REDUCTION
205
+ elif new_trust_radius >= MIN_TRUST_REDUCTION * trust_radius:
206
+ trust_radius = new_trust_radius
207
+ else:
208
+ trust_radius *= MIN_TRUST_REDUCTION
209
+
210
+ # Update iteration
211
+ if reduction_ratio >= SUFFICIENT_REDUCTION_RATIO:
212
+ x = x_next
213
+ f, b = f_next, b_next
214
+ c, A = grad_and_jac(x)
215
+ S = scaling(x)
216
+ # Get projections
217
+ Z, LS, Y = projections(A, factorization_method)
218
+ # Compute least-square lagrange multipliers
219
+ v = -LS.dot(c)
220
+ # Compute Hessian
221
+ H = lagr_hess(x, v)
222
+ # Set Flag
223
+ last_iteration_failed = False
224
+ # Otimality values
225
+ optimality = norm(c + A.T.dot(v), np.inf)
226
+ constr_violation = norm(b, np.inf) if len(b) > 0 else 0
227
+ else:
228
+ penalty = previous_penalty
229
+ last_iteration_failed = True
230
+
231
+ return x, state
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import numpy as np
3
+ from scipy.sparse.linalg import LinearOperator
4
+ from .._differentiable_functions import VectorFunction
5
+ from .._constraints import (
6
+ NonlinearConstraint, LinearConstraint, PreparedConstraint, Bounds, strict_bounds)
7
+ from .._hessian_update_strategy import BFGS
8
+ from .._optimize import OptimizeResult
9
+ from .._differentiable_functions import ScalarFunction
10
+ from .equality_constrained_sqp import equality_constrained_sqp
11
+ from .canonical_constraint import (CanonicalConstraint,
12
+ initial_constraints_as_canonical)
13
+ from .tr_interior_point import tr_interior_point
14
+ from .report import BasicReport, SQPReport, IPReport
15
+
16
+
17
+ TERMINATION_MESSAGES = {
18
+ 0: "The maximum number of function evaluations is exceeded.",
19
+ 1: "`gtol` termination condition is satisfied.",
20
+ 2: "`xtol` termination condition is satisfied.",
21
+ 3: "`callback` function requested termination."
22
+ }
23
+
24
+
25
+ class HessianLinearOperator:
26
+ """Build LinearOperator from hessp"""
27
+ def __init__(self, hessp, n):
28
+ self.hessp = hessp
29
+ self.n = n
30
+
31
+ def __call__(self, x, *args):
32
+ def matvec(p):
33
+ return self.hessp(x, p, *args)
34
+
35
+ return LinearOperator((self.n, self.n), matvec=matvec)
36
+
37
+
38
+ class LagrangianHessian:
39
+ """The Hessian of the Lagrangian as LinearOperator.
40
+
41
+ The Lagrangian is computed as the objective function plus all the
42
+ constraints multiplied with some numbers (Lagrange multipliers).
43
+ """
44
+ def __init__(self, n, objective_hess, constraints_hess):
45
+ self.n = n
46
+ self.objective_hess = objective_hess
47
+ self.constraints_hess = constraints_hess
48
+
49
+ def __call__(self, x, v_eq=np.empty(0), v_ineq=np.empty(0)):
50
+ H_objective = self.objective_hess(x)
51
+ H_constraints = self.constraints_hess(x, v_eq, v_ineq)
52
+
53
+ def matvec(p):
54
+ return H_objective.dot(p) + H_constraints.dot(p)
55
+
56
+ return LinearOperator((self.n, self.n), matvec)
57
+
58
+
59
+ def update_state_sqp(state, x, last_iteration_failed, objective, prepared_constraints,
60
+ start_time, tr_radius, constr_penalty, cg_info):
61
+ state.nit += 1
62
+ state.nfev = objective.nfev
63
+ state.njev = objective.ngev
64
+ state.nhev = objective.nhev
65
+ state.constr_nfev = [c.fun.nfev if isinstance(c.fun, VectorFunction) else 0
66
+ for c in prepared_constraints]
67
+ state.constr_njev = [c.fun.njev if isinstance(c.fun, VectorFunction) else 0
68
+ for c in prepared_constraints]
69
+ state.constr_nhev = [c.fun.nhev if isinstance(c.fun, VectorFunction) else 0
70
+ for c in prepared_constraints]
71
+
72
+ if not last_iteration_failed:
73
+ state.x = x
74
+ state.fun = objective.f
75
+ state.grad = objective.g
76
+ state.v = [c.fun.v for c in prepared_constraints]
77
+ state.constr = [c.fun.f for c in prepared_constraints]
78
+ state.jac = [c.fun.J for c in prepared_constraints]
79
+ # Compute Lagrangian Gradient
80
+ state.lagrangian_grad = np.copy(state.grad)
81
+ for c in prepared_constraints:
82
+ state.lagrangian_grad += c.fun.J.T.dot(c.fun.v)
83
+ state.optimality = np.linalg.norm(state.lagrangian_grad, np.inf)
84
+ # Compute maximum constraint violation
85
+ state.constr_violation = 0
86
+ for i in range(len(prepared_constraints)):
87
+ lb, ub = prepared_constraints[i].bounds
88
+ c = state.constr[i]
89
+ state.constr_violation = np.max([state.constr_violation,
90
+ np.max(lb - c),
91
+ np.max(c - ub)])
92
+
93
+ state.execution_time = time.time() - start_time
94
+ state.tr_radius = tr_radius
95
+ state.constr_penalty = constr_penalty
96
+ state.cg_niter += cg_info["niter"]
97
+ state.cg_stop_cond = cg_info["stop_cond"]
98
+
99
+ return state
100
+
101
+
102
+ def update_state_ip(state, x, last_iteration_failed, objective,
103
+ prepared_constraints, start_time,
104
+ tr_radius, constr_penalty, cg_info,
105
+ barrier_parameter, barrier_tolerance):
106
+ state = update_state_sqp(state, x, last_iteration_failed, objective,
107
+ prepared_constraints, start_time, tr_radius,
108
+ constr_penalty, cg_info)
109
+ state.barrier_parameter = barrier_parameter
110
+ state.barrier_tolerance = barrier_tolerance
111
+ return state
112
+
113
+
114
+ def _minimize_trustregion_constr(fun, x0, args, grad,
115
+ hess, hessp, bounds, constraints,
116
+ xtol=1e-8, gtol=1e-8,
117
+ barrier_tol=1e-8,
118
+ sparse_jacobian=None,
119
+ callback=None, maxiter=1000,
120
+ verbose=0, finite_diff_rel_step=None,
121
+ initial_constr_penalty=1.0, initial_tr_radius=1.0,
122
+ initial_barrier_parameter=0.1,
123
+ initial_barrier_tolerance=0.1,
124
+ factorization_method=None,
125
+ disp=False):
126
+ """Minimize a scalar function subject to constraints.
127
+
128
+ Parameters
129
+ ----------
130
+ gtol : float, optional
131
+ Tolerance for termination by the norm of the Lagrangian gradient.
132
+ The algorithm will terminate when both the infinity norm (i.e., max
133
+ abs value) of the Lagrangian gradient and the constraint violation
134
+ are smaller than ``gtol``. Default is 1e-8.
135
+ xtol : float, optional
136
+ Tolerance for termination by the change of the independent variable.
137
+ The algorithm will terminate when ``tr_radius < xtol``, where
138
+ ``tr_radius`` is the radius of the trust region used in the algorithm.
139
+ Default is 1e-8.
140
+ barrier_tol : float, optional
141
+ Threshold on the barrier parameter for the algorithm termination.
142
+ When inequality constraints are present, the algorithm will terminate
143
+ only when the barrier parameter is less than `barrier_tol`.
144
+ Default is 1e-8.
145
+ sparse_jacobian : {bool, None}, optional
146
+ Determines how to represent Jacobians of the constraints. If bool,
147
+ then Jacobians of all the constraints will be converted to the
148
+ corresponding format. If None (default), then Jacobians won't be
149
+ converted, but the algorithm can proceed only if they all have the
150
+ same format.
151
+ initial_tr_radius: float, optional
152
+ Initial trust radius. The trust radius gives the maximum distance
153
+ between solution points in consecutive iterations. It reflects the
154
+ trust the algorithm puts in the local approximation of the optimization
155
+ problem. For an accurate local approximation the trust-region should be
156
+ large and for an approximation valid only close to the current point it
157
+ should be a small one. The trust radius is automatically updated throughout
158
+ the optimization process, with ``initial_tr_radius`` being its initial value.
159
+ Default is 1 (recommended in [1]_, p. 19).
160
+ initial_constr_penalty : float, optional
161
+ Initial constraints penalty parameter. The penalty parameter is used for
162
+ balancing the requirements of decreasing the objective function
163
+ and satisfying the constraints. It is used for defining the merit function:
164
+ ``merit_function(x) = fun(x) + constr_penalty * constr_norm_l2(x)``,
165
+ where ``constr_norm_l2(x)`` is the l2 norm of a vector containing all
166
+ the constraints. The merit function is used for accepting or rejecting
167
+ trial points and ``constr_penalty`` weights the two conflicting goals
168
+ of reducing objective function and constraints. The penalty is automatically
169
+ updated throughout the optimization process, with
170
+ ``initial_constr_penalty`` being its initial value. Default is 1
171
+ (recommended in [1]_, p 19).
172
+ initial_barrier_parameter, initial_barrier_tolerance: float, optional
173
+ Initial barrier parameter and initial tolerance for the barrier subproblem.
174
+ Both are used only when inequality constraints are present. For dealing with
175
+ optimization problems ``min_x f(x)`` subject to inequality constraints
176
+ ``c(x) <= 0`` the algorithm introduces slack variables, solving the problem
177
+ ``min_(x,s) f(x) + barrier_parameter*sum(ln(s))`` subject to the equality
178
+ constraints ``c(x) + s = 0`` instead of the original problem. This subproblem
179
+ is solved for decreasing values of ``barrier_parameter`` and with decreasing
180
+ tolerances for the termination, starting with ``initial_barrier_parameter``
181
+ for the barrier parameter and ``initial_barrier_tolerance`` for the
182
+ barrier tolerance. Default is 0.1 for both values (recommended in [1]_ p. 19).
183
+ Also note that ``barrier_parameter`` and ``barrier_tolerance`` are updated
184
+ with the same prefactor.
185
+ factorization_method : string or None, optional
186
+ Method to factorize the Jacobian of the constraints. Use None (default)
187
+ for the auto selection or one of:
188
+
189
+ - 'NormalEquation' (requires scikit-sparse)
190
+ - 'AugmentedSystem'
191
+ - 'QRFactorization'
192
+ - 'SVDFactorization'
193
+
194
+ The methods 'NormalEquation' and 'AugmentedSystem' can be used only
195
+ with sparse constraints. The projections required by the algorithm
196
+ will be computed using, respectively, the normal equation and the
197
+ augmented system approaches explained in [1]_. 'NormalEquation'
198
+ computes the Cholesky factorization of ``A A.T`` and 'AugmentedSystem'
199
+ performs the LU factorization of an augmented system. They usually
200
+ provide similar results. 'AugmentedSystem' is used by default for
201
+ sparse matrices.
202
+
203
+ The methods 'QRFactorization' and 'SVDFactorization' can be used
204
+ only with dense constraints. They compute the required projections
205
+ using, respectively, QR and SVD factorizations. The 'SVDFactorization'
206
+ method can cope with Jacobian matrices with deficient row rank and will
207
+ be used whenever other factorization methods fail (which may imply the
208
+ conversion of sparse matrices to a dense format when required).
209
+ By default, 'QRFactorization' is used for dense matrices.
210
+ finite_diff_rel_step : None or array_like, optional
211
+ Relative step size for the finite difference approximation.
212
+ maxiter : int, optional
213
+ Maximum number of algorithm iterations. Default is 1000.
214
+ verbose : {0, 1, 2}, optional
215
+ Level of algorithm's verbosity:
216
+
217
+ * 0 (default) : work silently.
218
+ * 1 : display a termination report.
219
+ * 2 : display progress during iterations.
220
+ * 3 : display progress during iterations (more complete report).
221
+
222
+ disp : bool, optional
223
+ If True (default), then `verbose` will be set to 1 if it was 0.
224
+
225
+ Returns
226
+ -------
227
+ `OptimizeResult` with the fields documented below. Note the following:
228
+
229
+ 1. All values corresponding to the constraints are ordered as they
230
+ were passed to the solver. And values corresponding to `bounds`
231
+ constraints are put *after* other constraints.
232
+ 2. All numbers of function, Jacobian or Hessian evaluations correspond
233
+ to numbers of actual Python function calls. It means, for example,
234
+ that if a Jacobian is estimated by finite differences, then the
235
+ number of Jacobian evaluations will be zero and the number of
236
+ function evaluations will be incremented by all calls during the
237
+ finite difference estimation.
238
+
239
+ x : ndarray, shape (n,)
240
+ Solution found.
241
+ optimality : float
242
+ Infinity norm of the Lagrangian gradient at the solution.
243
+ constr_violation : float
244
+ Maximum constraint violation at the solution.
245
+ fun : float
246
+ Objective function at the solution.
247
+ grad : ndarray, shape (n,)
248
+ Gradient of the objective function at the solution.
249
+ lagrangian_grad : ndarray, shape (n,)
250
+ Gradient of the Lagrangian function at the solution.
251
+ nit : int
252
+ Total number of iterations.
253
+ nfev : integer
254
+ Number of the objective function evaluations.
255
+ njev : integer
256
+ Number of the objective function gradient evaluations.
257
+ nhev : integer
258
+ Number of the objective function Hessian evaluations.
259
+ cg_niter : int
260
+ Total number of the conjugate gradient method iterations.
261
+ method : {'equality_constrained_sqp', 'tr_interior_point'}
262
+ Optimization method used.
263
+ constr : list of ndarray
264
+ List of constraint values at the solution.
265
+ jac : list of {ndarray, sparse matrix}
266
+ List of the Jacobian matrices of the constraints at the solution.
267
+ v : list of ndarray
268
+ List of the Lagrange multipliers for the constraints at the solution.
269
+ For an inequality constraint a positive multiplier means that the upper
270
+ bound is active, a negative multiplier means that the lower bound is
271
+ active and if a multiplier is zero it means the constraint is not
272
+ active.
273
+ constr_nfev : list of int
274
+ Number of constraint evaluations for each of the constraints.
275
+ constr_njev : list of int
276
+ Number of Jacobian matrix evaluations for each of the constraints.
277
+ constr_nhev : list of int
278
+ Number of Hessian evaluations for each of the constraints.
279
+ tr_radius : float
280
+ Radius of the trust region at the last iteration.
281
+ constr_penalty : float
282
+ Penalty parameter at the last iteration, see `initial_constr_penalty`.
283
+ barrier_tolerance : float
284
+ Tolerance for the barrier subproblem at the last iteration.
285
+ Only for problems with inequality constraints.
286
+ barrier_parameter : float
287
+ Barrier parameter at the last iteration. Only for problems
288
+ with inequality constraints.
289
+ execution_time : float
290
+ Total execution time.
291
+ message : str
292
+ Termination message.
293
+ status : {0, 1, 2, 3}
294
+ Termination status:
295
+
296
+ * 0 : The maximum number of function evaluations is exceeded.
297
+ * 1 : `gtol` termination condition is satisfied.
298
+ * 2 : `xtol` termination condition is satisfied.
299
+ * 3 : `callback` function requested termination.
300
+
301
+ cg_stop_cond : int
302
+ Reason for CG subproblem termination at the last iteration:
303
+
304
+ * 0 : CG subproblem not evaluated.
305
+ * 1 : Iteration limit was reached.
306
+ * 2 : Reached the trust-region boundary.
307
+ * 3 : Negative curvature detected.
308
+ * 4 : Tolerance was satisfied.
309
+
310
+ References
311
+ ----------
312
+ .. [1] Conn, A. R., Gould, N. I., & Toint, P. L.
313
+ Trust region methods. 2000. Siam. pp. 19.
314
+ """
315
+ x0 = np.atleast_1d(x0).astype(float)
316
+ n_vars = np.size(x0)
317
+ if hess is None:
318
+ if callable(hessp):
319
+ hess = HessianLinearOperator(hessp, n_vars)
320
+ else:
321
+ hess = BFGS()
322
+ if disp and verbose == 0:
323
+ verbose = 1
324
+
325
+ if bounds is not None:
326
+ modified_lb = np.nextafter(bounds.lb, -np.inf, where=bounds.lb > -np.inf)
327
+ modified_ub = np.nextafter(bounds.ub, np.inf, where=bounds.ub < np.inf)
328
+ modified_lb = np.where(np.isfinite(bounds.lb), modified_lb, bounds.lb)
329
+ modified_ub = np.where(np.isfinite(bounds.ub), modified_ub, bounds.ub)
330
+ bounds = Bounds(modified_lb, modified_ub, keep_feasible=bounds.keep_feasible)
331
+ finite_diff_bounds = strict_bounds(bounds.lb, bounds.ub,
332
+ bounds.keep_feasible, n_vars)
333
+ else:
334
+ finite_diff_bounds = (-np.inf, np.inf)
335
+
336
+ # Define Objective Function
337
+ objective = ScalarFunction(fun, x0, args, grad, hess,
338
+ finite_diff_rel_step, finite_diff_bounds)
339
+
340
+ # Put constraints in list format when needed.
341
+ if isinstance(constraints, (NonlinearConstraint, LinearConstraint)):
342
+ constraints = [constraints]
343
+
344
+ # Prepare constraints.
345
+ prepared_constraints = [
346
+ PreparedConstraint(c, x0, sparse_jacobian, finite_diff_bounds)
347
+ for c in constraints]
348
+
349
+ # Check that all constraints are either sparse or dense.
350
+ n_sparse = sum(c.fun.sparse_jacobian for c in prepared_constraints)
351
+ if 0 < n_sparse < len(prepared_constraints):
352
+ raise ValueError("All constraints must have the same kind of the "
353
+ "Jacobian --- either all sparse or all dense. "
354
+ "You can set the sparsity globally by setting "
355
+ "`sparse_jacobian` to either True of False.")
356
+ if prepared_constraints:
357
+ sparse_jacobian = n_sparse > 0
358
+
359
+ if bounds is not None:
360
+ if sparse_jacobian is None:
361
+ sparse_jacobian = True
362
+ prepared_constraints.append(PreparedConstraint(bounds, x0,
363
+ sparse_jacobian))
364
+
365
+ # Concatenate initial constraints to the canonical form.
366
+ c_eq0, c_ineq0, J_eq0, J_ineq0 = initial_constraints_as_canonical(
367
+ n_vars, prepared_constraints, sparse_jacobian)
368
+
369
+ # Prepare all canonical constraints and concatenate it into one.
370
+ canonical_all = [CanonicalConstraint.from_PreparedConstraint(c)
371
+ for c in prepared_constraints]
372
+
373
+ if len(canonical_all) == 0:
374
+ canonical = CanonicalConstraint.empty(n_vars)
375
+ elif len(canonical_all) == 1:
376
+ canonical = canonical_all[0]
377
+ else:
378
+ canonical = CanonicalConstraint.concatenate(canonical_all,
379
+ sparse_jacobian)
380
+
381
+ # Generate the Hessian of the Lagrangian.
382
+ lagrangian_hess = LagrangianHessian(n_vars, objective.hess, canonical.hess)
383
+
384
+ # Choose appropriate method
385
+ if canonical.n_ineq == 0:
386
+ method = 'equality_constrained_sqp'
387
+ else:
388
+ method = 'tr_interior_point'
389
+
390
+ # Construct OptimizeResult
391
+ state = OptimizeResult(
392
+ nit=0, nfev=0, njev=0, nhev=0,
393
+ cg_niter=0, cg_stop_cond=0,
394
+ fun=objective.f, grad=objective.g,
395
+ lagrangian_grad=np.copy(objective.g),
396
+ constr=[c.fun.f for c in prepared_constraints],
397
+ jac=[c.fun.J for c in prepared_constraints],
398
+ constr_nfev=[0 for c in prepared_constraints],
399
+ constr_njev=[0 for c in prepared_constraints],
400
+ constr_nhev=[0 for c in prepared_constraints],
401
+ v=[c.fun.v for c in prepared_constraints],
402
+ method=method)
403
+
404
+ # Start counting
405
+ start_time = time.time()
406
+
407
+ # Define stop criteria
408
+ if method == 'equality_constrained_sqp':
409
+ def stop_criteria(state, x, last_iteration_failed,
410
+ optimality, constr_violation,
411
+ tr_radius, constr_penalty, cg_info):
412
+ state = update_state_sqp(state, x, last_iteration_failed,
413
+ objective, prepared_constraints,
414
+ start_time, tr_radius, constr_penalty,
415
+ cg_info)
416
+ if verbose == 2:
417
+ BasicReport.print_iteration(state.nit,
418
+ state.nfev,
419
+ state.cg_niter,
420
+ state.fun,
421
+ state.tr_radius,
422
+ state.optimality,
423
+ state.constr_violation)
424
+ elif verbose > 2:
425
+ SQPReport.print_iteration(state.nit,
426
+ state.nfev,
427
+ state.cg_niter,
428
+ state.fun,
429
+ state.tr_radius,
430
+ state.optimality,
431
+ state.constr_violation,
432
+ state.constr_penalty,
433
+ state.cg_stop_cond)
434
+ state.status = None
435
+ state.niter = state.nit # Alias for callback (backward-compatibility)
436
+ if callback is not None:
437
+ callback_stop = False
438
+ try:
439
+ callback_stop = callback(state)
440
+ except StopIteration:
441
+ callback_stop = True
442
+ if callback_stop:
443
+ state.status = 3
444
+ return True
445
+ if state.optimality < gtol and state.constr_violation < gtol:
446
+ state.status = 1
447
+ elif state.tr_radius < xtol:
448
+ state.status = 2
449
+ elif state.nit >= maxiter:
450
+ state.status = 0
451
+ return state.status in (0, 1, 2, 3)
452
+ elif method == 'tr_interior_point':
453
+ def stop_criteria(state, x, last_iteration_failed, tr_radius,
454
+ constr_penalty, cg_info, barrier_parameter,
455
+ barrier_tolerance):
456
+ state = update_state_ip(state, x, last_iteration_failed,
457
+ objective, prepared_constraints,
458
+ start_time, tr_radius, constr_penalty,
459
+ cg_info, barrier_parameter, barrier_tolerance)
460
+ if verbose == 2:
461
+ BasicReport.print_iteration(state.nit,
462
+ state.nfev,
463
+ state.cg_niter,
464
+ state.fun,
465
+ state.tr_radius,
466
+ state.optimality,
467
+ state.constr_violation)
468
+ elif verbose > 2:
469
+ IPReport.print_iteration(state.nit,
470
+ state.nfev,
471
+ state.cg_niter,
472
+ state.fun,
473
+ state.tr_radius,
474
+ state.optimality,
475
+ state.constr_violation,
476
+ state.constr_penalty,
477
+ state.barrier_parameter,
478
+ state.cg_stop_cond)
479
+ state.status = None
480
+ state.niter = state.nit # Alias for callback (backward compatibility)
481
+ if callback is not None:
482
+ callback_stop = False
483
+ try:
484
+ callback_stop = callback(state)
485
+ except StopIteration:
486
+ callback_stop = True
487
+ if callback_stop:
488
+ state.status = 3
489
+ return True
490
+ if state.optimality < gtol and state.constr_violation < gtol:
491
+ state.status = 1
492
+ elif (state.tr_radius < xtol
493
+ and state.barrier_parameter < barrier_tol):
494
+ state.status = 2
495
+ elif state.nit >= maxiter:
496
+ state.status = 0
497
+ return state.status in (0, 1, 2, 3)
498
+
499
+ if verbose == 2:
500
+ BasicReport.print_header()
501
+ elif verbose > 2:
502
+ if method == 'equality_constrained_sqp':
503
+ SQPReport.print_header()
504
+ elif method == 'tr_interior_point':
505
+ IPReport.print_header()
506
+
507
+ # Call inferior function to do the optimization
508
+ if method == 'equality_constrained_sqp':
509
+ def fun_and_constr(x):
510
+ f = objective.fun(x)
511
+ c_eq, _ = canonical.fun(x)
512
+ return f, c_eq
513
+
514
+ def grad_and_jac(x):
515
+ g = objective.grad(x)
516
+ J_eq, _ = canonical.jac(x)
517
+ return g, J_eq
518
+
519
+ _, result = equality_constrained_sqp(
520
+ fun_and_constr, grad_and_jac, lagrangian_hess,
521
+ x0, objective.f, objective.g,
522
+ c_eq0, J_eq0,
523
+ stop_criteria, state,
524
+ initial_constr_penalty, initial_tr_radius,
525
+ factorization_method)
526
+
527
+ elif method == 'tr_interior_point':
528
+ _, result = tr_interior_point(
529
+ objective.fun, objective.grad, lagrangian_hess,
530
+ n_vars, canonical.n_ineq, canonical.n_eq,
531
+ canonical.fun, canonical.jac,
532
+ x0, objective.f, objective.g,
533
+ c_ineq0, J_ineq0, c_eq0, J_eq0,
534
+ stop_criteria,
535
+ canonical.keep_feasible,
536
+ xtol, state, initial_barrier_parameter,
537
+ initial_barrier_tolerance,
538
+ initial_constr_penalty, initial_tr_radius,
539
+ factorization_method)
540
+
541
+ # Status 3 occurs when the callback function requests termination,
542
+ # this is assumed to not be a success.
543
+ result.success = True if result.status in (1, 2) else False
544
+ result.message = TERMINATION_MESSAGES[result.status]
545
+
546
+ # Alias (for backward compatibility with 1.1.0)
547
+ result.niter = result.nit
548
+
549
+ if verbose == 2:
550
+ BasicReport.print_footer()
551
+ elif verbose > 2:
552
+ if method == 'equality_constrained_sqp':
553
+ SQPReport.print_footer()
554
+ elif method == 'tr_interior_point':
555
+ IPReport.print_footer()
556
+ if verbose >= 1:
557
+ print(result.message)
558
+ print("Number of iterations: {}, function evaluations: {}, "
559
+ "CG iterations: {}, optimality: {:.2e}, "
560
+ "constraint violation: {:.2e}, execution time: {:4.2} s."
561
+ .format(result.nit, result.nfev, result.cg_niter,
562
+ result.optimality, result.constr_violation,
563
+ result.execution_time))
564
+ return result
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/projections.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Basic linear factorizations needed by the solver."""
2
+
3
+ from scipy.sparse import (bmat, csc_matrix, eye, issparse)
4
+ from scipy.sparse.linalg import LinearOperator
5
+ import scipy.linalg
6
+ import scipy.sparse.linalg
7
+ try:
8
+ from sksparse.cholmod import cholesky_AAt
9
+ sksparse_available = True
10
+ except ImportError:
11
+ import warnings
12
+ sksparse_available = False
13
+ import numpy as np
14
+ from warnings import warn
15
+
16
+ __all__ = [
17
+ 'orthogonality',
18
+ 'projections',
19
+ ]
20
+
21
+
22
+ def orthogonality(A, g):
23
+ """Measure orthogonality between a vector and the null space of a matrix.
24
+
25
+ Compute a measure of orthogonality between the null space
26
+ of the (possibly sparse) matrix ``A`` and a given vector ``g``.
27
+
28
+ The formula is a simplified (and cheaper) version of formula (3.13)
29
+ from [1]_.
30
+ ``orth = norm(A g, ord=2)/(norm(A, ord='fro')*norm(g, ord=2))``.
31
+
32
+ References
33
+ ----------
34
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
35
+ "On the solution of equality constrained quadratic
36
+ programming problems arising in optimization."
37
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
38
+ """
39
+ # Compute vector norms
40
+ norm_g = np.linalg.norm(g)
41
+ # Compute Froebnius norm of the matrix A
42
+ if issparse(A):
43
+ norm_A = scipy.sparse.linalg.norm(A, ord='fro')
44
+ else:
45
+ norm_A = np.linalg.norm(A, ord='fro')
46
+
47
+ # Check if norms are zero
48
+ if norm_g == 0 or norm_A == 0:
49
+ return 0
50
+
51
+ norm_A_g = np.linalg.norm(A.dot(g))
52
+ # Orthogonality measure
53
+ orth = norm_A_g / (norm_A*norm_g)
54
+ return orth
55
+
56
+
57
+ def normal_equation_projections(A, m, n, orth_tol, max_refin, tol):
58
+ """Return linear operators for matrix A using ``NormalEquation`` approach.
59
+ """
60
+ # Cholesky factorization
61
+ factor = cholesky_AAt(A)
62
+
63
+ # z = x - A.T inv(A A.T) A x
64
+ def null_space(x):
65
+ v = factor(A.dot(x))
66
+ z = x - A.T.dot(v)
67
+
68
+ # Iterative refinement to improve roundoff
69
+ # errors described in [2]_, algorithm 5.1.
70
+ k = 0
71
+ while orthogonality(A, z) > orth_tol:
72
+ if k >= max_refin:
73
+ break
74
+ # z_next = z - A.T inv(A A.T) A z
75
+ v = factor(A.dot(z))
76
+ z = z - A.T.dot(v)
77
+ k += 1
78
+
79
+ return z
80
+
81
+ # z = inv(A A.T) A x
82
+ def least_squares(x):
83
+ return factor(A.dot(x))
84
+
85
+ # z = A.T inv(A A.T) x
86
+ def row_space(x):
87
+ return A.T.dot(factor(x))
88
+
89
+ return null_space, least_squares, row_space
90
+
91
+
92
+ def augmented_system_projections(A, m, n, orth_tol, max_refin, tol):
93
+ """Return linear operators for matrix A - ``AugmentedSystem``."""
94
+ # Form augmented system
95
+ K = csc_matrix(bmat([[eye(n), A.T], [A, None]]))
96
+ # LU factorization
97
+ # TODO: Use a symmetric indefinite factorization
98
+ # to solve the system twice as fast (because
99
+ # of the symmetry).
100
+ try:
101
+ solve = scipy.sparse.linalg.factorized(K)
102
+ except RuntimeError:
103
+ warn("Singular Jacobian matrix. Using dense SVD decomposition to "
104
+ "perform the factorizations.",
105
+ stacklevel=3)
106
+ return svd_factorization_projections(A.toarray(),
107
+ m, n, orth_tol,
108
+ max_refin, tol)
109
+
110
+ # z = x - A.T inv(A A.T) A x
111
+ # is computed solving the extended system:
112
+ # [I A.T] * [ z ] = [x]
113
+ # [A O ] [aux] [0]
114
+ def null_space(x):
115
+ # v = [x]
116
+ # [0]
117
+ v = np.hstack([x, np.zeros(m)])
118
+ # lu_sol = [ z ]
119
+ # [aux]
120
+ lu_sol = solve(v)
121
+ z = lu_sol[:n]
122
+
123
+ # Iterative refinement to improve roundoff
124
+ # errors described in [2]_, algorithm 5.2.
125
+ k = 0
126
+ while orthogonality(A, z) > orth_tol:
127
+ if k >= max_refin:
128
+ break
129
+ # new_v = [x] - [I A.T] * [ z ]
130
+ # [0] [A O ] [aux]
131
+ new_v = v - K.dot(lu_sol)
132
+ # [I A.T] * [delta z ] = new_v
133
+ # [A O ] [delta aux]
134
+ lu_update = solve(new_v)
135
+ # [ z ] += [delta z ]
136
+ # [aux] [delta aux]
137
+ lu_sol += lu_update
138
+ z = lu_sol[:n]
139
+ k += 1
140
+
141
+ # return z = x - A.T inv(A A.T) A x
142
+ return z
143
+
144
+ # z = inv(A A.T) A x
145
+ # is computed solving the extended system:
146
+ # [I A.T] * [aux] = [x]
147
+ # [A O ] [ z ] [0]
148
+ def least_squares(x):
149
+ # v = [x]
150
+ # [0]
151
+ v = np.hstack([x, np.zeros(m)])
152
+ # lu_sol = [aux]
153
+ # [ z ]
154
+ lu_sol = solve(v)
155
+ # return z = inv(A A.T) A x
156
+ return lu_sol[n:m+n]
157
+
158
+ # z = A.T inv(A A.T) x
159
+ # is computed solving the extended system:
160
+ # [I A.T] * [ z ] = [0]
161
+ # [A O ] [aux] [x]
162
+ def row_space(x):
163
+ # v = [0]
164
+ # [x]
165
+ v = np.hstack([np.zeros(n), x])
166
+ # lu_sol = [ z ]
167
+ # [aux]
168
+ lu_sol = solve(v)
169
+ # return z = A.T inv(A A.T) x
170
+ return lu_sol[:n]
171
+
172
+ return null_space, least_squares, row_space
173
+
174
+
175
+ def qr_factorization_projections(A, m, n, orth_tol, max_refin, tol):
176
+ """Return linear operators for matrix A using ``QRFactorization`` approach.
177
+ """
178
+ # QRFactorization
179
+ Q, R, P = scipy.linalg.qr(A.T, pivoting=True, mode='economic')
180
+
181
+ if np.linalg.norm(R[-1, :], np.inf) < tol:
182
+ warn('Singular Jacobian matrix. Using SVD decomposition to ' +
183
+ 'perform the factorizations.',
184
+ stacklevel=3)
185
+ return svd_factorization_projections(A, m, n,
186
+ orth_tol,
187
+ max_refin,
188
+ tol)
189
+
190
+ # z = x - A.T inv(A A.T) A x
191
+ def null_space(x):
192
+ # v = P inv(R) Q.T x
193
+ aux1 = Q.T.dot(x)
194
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
195
+ v = np.zeros(m)
196
+ v[P] = aux2
197
+ z = x - A.T.dot(v)
198
+
199
+ # Iterative refinement to improve roundoff
200
+ # errors described in [2]_, algorithm 5.1.
201
+ k = 0
202
+ while orthogonality(A, z) > orth_tol:
203
+ if k >= max_refin:
204
+ break
205
+ # v = P inv(R) Q.T x
206
+ aux1 = Q.T.dot(z)
207
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
208
+ v[P] = aux2
209
+ # z_next = z - A.T v
210
+ z = z - A.T.dot(v)
211
+ k += 1
212
+
213
+ return z
214
+
215
+ # z = inv(A A.T) A x
216
+ def least_squares(x):
217
+ # z = P inv(R) Q.T x
218
+ aux1 = Q.T.dot(x)
219
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
220
+ z = np.zeros(m)
221
+ z[P] = aux2
222
+ return z
223
+
224
+ # z = A.T inv(A A.T) x
225
+ def row_space(x):
226
+ # z = Q inv(R.T) P.T x
227
+ aux1 = x[P]
228
+ aux2 = scipy.linalg.solve_triangular(R, aux1,
229
+ lower=False,
230
+ trans='T')
231
+ z = Q.dot(aux2)
232
+ return z
233
+
234
+ return null_space, least_squares, row_space
235
+
236
+
237
+ def svd_factorization_projections(A, m, n, orth_tol, max_refin, tol):
238
+ """Return linear operators for matrix A using ``SVDFactorization`` approach.
239
+ """
240
+ # SVD Factorization
241
+ U, s, Vt = scipy.linalg.svd(A, full_matrices=False)
242
+
243
+ # Remove dimensions related with very small singular values
244
+ U = U[:, s > tol]
245
+ Vt = Vt[s > tol, :]
246
+ s = s[s > tol]
247
+
248
+ # z = x - A.T inv(A A.T) A x
249
+ def null_space(x):
250
+ # v = U 1/s V.T x = inv(A A.T) A x
251
+ aux1 = Vt.dot(x)
252
+ aux2 = 1/s*aux1
253
+ v = U.dot(aux2)
254
+ z = x - A.T.dot(v)
255
+
256
+ # Iterative refinement to improve roundoff
257
+ # errors described in [2]_, algorithm 5.1.
258
+ k = 0
259
+ while orthogonality(A, z) > orth_tol:
260
+ if k >= max_refin:
261
+ break
262
+ # v = U 1/s V.T x = inv(A A.T) A x
263
+ aux1 = Vt.dot(z)
264
+ aux2 = 1/s*aux1
265
+ v = U.dot(aux2)
266
+ # z_next = z - A.T v
267
+ z = z - A.T.dot(v)
268
+ k += 1
269
+
270
+ return z
271
+
272
+ # z = inv(A A.T) A x
273
+ def least_squares(x):
274
+ # z = U 1/s V.T x = inv(A A.T) A x
275
+ aux1 = Vt.dot(x)
276
+ aux2 = 1/s*aux1
277
+ z = U.dot(aux2)
278
+ return z
279
+
280
+ # z = A.T inv(A A.T) x
281
+ def row_space(x):
282
+ # z = V 1/s U.T x
283
+ aux1 = U.T.dot(x)
284
+ aux2 = 1/s*aux1
285
+ z = Vt.T.dot(aux2)
286
+ return z
287
+
288
+ return null_space, least_squares, row_space
289
+
290
+
291
+ def projections(A, method=None, orth_tol=1e-12, max_refin=3, tol=1e-15):
292
+ """Return three linear operators related with a given matrix A.
293
+
294
+ Parameters
295
+ ----------
296
+ A : sparse matrix (or ndarray), shape (m, n)
297
+ Matrix ``A`` used in the projection.
298
+ method : string, optional
299
+ Method used for compute the given linear
300
+ operators. Should be one of:
301
+
302
+ - 'NormalEquation': The operators
303
+ will be computed using the
304
+ so-called normal equation approach
305
+ explained in [1]_. In order to do
306
+ so the Cholesky factorization of
307
+ ``(A A.T)`` is computed. Exclusive
308
+ for sparse matrices.
309
+ - 'AugmentedSystem': The operators
310
+ will be computed using the
311
+ so-called augmented system approach
312
+ explained in [1]_. Exclusive
313
+ for sparse matrices.
314
+ - 'QRFactorization': Compute projections
315
+ using QR factorization. Exclusive for
316
+ dense matrices.
317
+ - 'SVDFactorization': Compute projections
318
+ using SVD factorization. Exclusive for
319
+ dense matrices.
320
+
321
+ orth_tol : float, optional
322
+ Tolerance for iterative refinements.
323
+ max_refin : int, optional
324
+ Maximum number of iterative refinements.
325
+ tol : float, optional
326
+ Tolerance for singular values.
327
+
328
+ Returns
329
+ -------
330
+ Z : LinearOperator, shape (n, n)
331
+ Null-space operator. For a given vector ``x``,
332
+ the null space operator is equivalent to apply
333
+ a projection matrix ``P = I - A.T inv(A A.T) A``
334
+ to the vector. It can be shown that this is
335
+ equivalent to project ``x`` into the null space
336
+ of A.
337
+ LS : LinearOperator, shape (m, n)
338
+ Least-squares operator. For a given vector ``x``,
339
+ the least-squares operator is equivalent to apply a
340
+ pseudoinverse matrix ``pinv(A.T) = inv(A A.T) A``
341
+ to the vector. It can be shown that this vector
342
+ ``pinv(A.T) x`` is the least_square solution to
343
+ ``A.T y = x``.
344
+ Y : LinearOperator, shape (n, m)
345
+ Row-space operator. For a given vector ``x``,
346
+ the row-space operator is equivalent to apply a
347
+ projection matrix ``Q = A.T inv(A A.T)``
348
+ to the vector. It can be shown that this
349
+ vector ``y = Q x`` the minimum norm solution
350
+ of ``A y = x``.
351
+
352
+ Notes
353
+ -----
354
+ Uses iterative refinements described in [1]
355
+ during the computation of ``Z`` in order to
356
+ cope with the possibility of large roundoff errors.
357
+
358
+ References
359
+ ----------
360
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
361
+ "On the solution of equality constrained quadratic
362
+ programming problems arising in optimization."
363
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
364
+ """
365
+ m, n = np.shape(A)
366
+
367
+ # The factorization of an empty matrix
368
+ # only works for the sparse representation.
369
+ if m*n == 0:
370
+ A = csc_matrix(A)
371
+
372
+ # Check Argument
373
+ if issparse(A):
374
+ if method is None:
375
+ method = "AugmentedSystem"
376
+ if method not in ("NormalEquation", "AugmentedSystem"):
377
+ raise ValueError("Method not allowed for sparse matrix.")
378
+ if method == "NormalEquation" and not sksparse_available:
379
+ warnings.warn("Only accepts 'NormalEquation' option when "
380
+ "scikit-sparse is available. Using "
381
+ "'AugmentedSystem' option instead.",
382
+ ImportWarning, stacklevel=3)
383
+ method = 'AugmentedSystem'
384
+ else:
385
+ if method is None:
386
+ method = "QRFactorization"
387
+ if method not in ("QRFactorization", "SVDFactorization"):
388
+ raise ValueError("Method not allowed for dense array.")
389
+
390
+ if method == 'NormalEquation':
391
+ null_space, least_squares, row_space \
392
+ = normal_equation_projections(A, m, n, orth_tol, max_refin, tol)
393
+ elif method == 'AugmentedSystem':
394
+ null_space, least_squares, row_space \
395
+ = augmented_system_projections(A, m, n, orth_tol, max_refin, tol)
396
+ elif method == "QRFactorization":
397
+ null_space, least_squares, row_space \
398
+ = qr_factorization_projections(A, m, n, orth_tol, max_refin, tol)
399
+ elif method == "SVDFactorization":
400
+ null_space, least_squares, row_space \
401
+ = svd_factorization_projections(A, m, n, orth_tol, max_refin, tol)
402
+
403
+ Z = LinearOperator((n, n), null_space)
404
+ LS = LinearOperator((m, n), least_squares)
405
+ Y = LinearOperator((n, m), row_space)
406
+
407
+ return Z, LS, Y
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py ADDED
@@ -0,0 +1,637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Equality-constrained quadratic programming solvers."""
2
+
3
+ from scipy.sparse import (linalg, bmat, csc_matrix)
4
+ from math import copysign
5
+ import numpy as np
6
+ from numpy.linalg import norm
7
+
8
+ __all__ = [
9
+ 'eqp_kktfact',
10
+ 'sphere_intersections',
11
+ 'box_intersections',
12
+ 'box_sphere_intersections',
13
+ 'inside_box_boundaries',
14
+ 'modified_dogleg',
15
+ 'projected_cg'
16
+ ]
17
+
18
+
19
+ # For comparison with the projected CG
20
+ def eqp_kktfact(H, c, A, b):
21
+ """Solve equality-constrained quadratic programming (EQP) problem.
22
+
23
+ Solve ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0``
24
+ using direct factorization of the KKT system.
25
+
26
+ Parameters
27
+ ----------
28
+ H : sparse matrix, shape (n, n)
29
+ Hessian matrix of the EQP problem.
30
+ c : array_like, shape (n,)
31
+ Gradient of the quadratic objective function.
32
+ A : sparse matrix
33
+ Jacobian matrix of the EQP problem.
34
+ b : array_like, shape (m,)
35
+ Right-hand side of the constraint equation.
36
+
37
+ Returns
38
+ -------
39
+ x : array_like, shape (n,)
40
+ Solution of the KKT problem.
41
+ lagrange_multipliers : ndarray, shape (m,)
42
+ Lagrange multipliers of the KKT problem.
43
+ """
44
+ n, = np.shape(c) # Number of parameters
45
+ m, = np.shape(b) # Number of constraints
46
+
47
+ # Karush-Kuhn-Tucker matrix of coefficients.
48
+ # Defined as in Nocedal/Wright "Numerical
49
+ # Optimization" p.452 in Eq. (16.4).
50
+ kkt_matrix = csc_matrix(bmat([[H, A.T], [A, None]]))
51
+ # Vector of coefficients.
52
+ kkt_vec = np.hstack([-c, -b])
53
+
54
+ # TODO: Use a symmetric indefinite factorization
55
+ # to solve the system twice as fast (because
56
+ # of the symmetry).
57
+ lu = linalg.splu(kkt_matrix)
58
+ kkt_sol = lu.solve(kkt_vec)
59
+ x = kkt_sol[:n]
60
+ lagrange_multipliers = -kkt_sol[n:n+m]
61
+
62
+ return x, lagrange_multipliers
63
+
64
+
65
+ def sphere_intersections(z, d, trust_radius,
66
+ entire_line=False):
67
+ """Find the intersection between segment (or line) and spherical constraints.
68
+
69
+ Find the intersection between the segment (or line) defined by the
70
+ parametric equation ``x(t) = z + t*d`` and the ball
71
+ ``||x|| <= trust_radius``.
72
+
73
+ Parameters
74
+ ----------
75
+ z : array_like, shape (n,)
76
+ Initial point.
77
+ d : array_like, shape (n,)
78
+ Direction.
79
+ trust_radius : float
80
+ Ball radius.
81
+ entire_line : bool, optional
82
+ When ``True``, the function returns the intersection between the line
83
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the ball
84
+ ``||x|| <= trust_radius``. When ``False``, the function returns the intersection
85
+ between the segment ``x(t) = z + t*d``, ``0 <= t <= 1``, and the ball.
86
+
87
+ Returns
88
+ -------
89
+ ta, tb : float
90
+ The line/segment ``x(t) = z + t*d`` is inside the ball for
91
+ for ``ta <= t <= tb``.
92
+ intersect : bool
93
+ When ``True``, there is a intersection between the line/segment
94
+ and the sphere. On the other hand, when ``False``, there is no
95
+ intersection.
96
+ """
97
+ # Special case when d=0
98
+ if norm(d) == 0:
99
+ return 0, 0, False
100
+ # Check for inf trust_radius
101
+ if np.isinf(trust_radius):
102
+ if entire_line:
103
+ ta = -np.inf
104
+ tb = np.inf
105
+ else:
106
+ ta = 0
107
+ tb = 1
108
+ intersect = True
109
+ return ta, tb, intersect
110
+
111
+ a = np.dot(d, d)
112
+ b = 2 * np.dot(z, d)
113
+ c = np.dot(z, z) - trust_radius**2
114
+ discriminant = b*b - 4*a*c
115
+ if discriminant < 0:
116
+ intersect = False
117
+ return 0, 0, intersect
118
+ sqrt_discriminant = np.sqrt(discriminant)
119
+
120
+ # The following calculation is mathematically
121
+ # equivalent to:
122
+ # ta = (-b - sqrt_discriminant) / (2*a)
123
+ # tb = (-b + sqrt_discriminant) / (2*a)
124
+ # but produce smaller round off errors.
125
+ # Look at Matrix Computation p.97
126
+ # for a better justification.
127
+ aux = b + copysign(sqrt_discriminant, b)
128
+ ta = -aux / (2*a)
129
+ tb = -2*c / aux
130
+ ta, tb = sorted([ta, tb])
131
+
132
+ if entire_line:
133
+ intersect = True
134
+ else:
135
+ # Checks to see if intersection happens
136
+ # within vectors length.
137
+ if tb < 0 or ta > 1:
138
+ intersect = False
139
+ ta = 0
140
+ tb = 0
141
+ else:
142
+ intersect = True
143
+ # Restrict intersection interval
144
+ # between 0 and 1.
145
+ ta = max(0, ta)
146
+ tb = min(1, tb)
147
+
148
+ return ta, tb, intersect
149
+
150
+
151
+ def box_intersections(z, d, lb, ub,
152
+ entire_line=False):
153
+ """Find the intersection between segment (or line) and box constraints.
154
+
155
+ Find the intersection between the segment (or line) defined by the
156
+ parametric equation ``x(t) = z + t*d`` and the rectangular box
157
+ ``lb <= x <= ub``.
158
+
159
+ Parameters
160
+ ----------
161
+ z : array_like, shape (n,)
162
+ Initial point.
163
+ d : array_like, shape (n,)
164
+ Direction.
165
+ lb : array_like, shape (n,)
166
+ Lower bounds to each one of the components of ``x``. Used
167
+ to delimit the rectangular box.
168
+ ub : array_like, shape (n, )
169
+ Upper bounds to each one of the components of ``x``. Used
170
+ to delimit the rectangular box.
171
+ entire_line : bool, optional
172
+ When ``True``, the function returns the intersection between the line
173
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the rectangular
174
+ box. When ``False``, the function returns the intersection between the segment
175
+ ``x(t) = z + t*d``, ``0 <= t <= 1``, and the rectangular box.
176
+
177
+ Returns
178
+ -------
179
+ ta, tb : float
180
+ The line/segment ``x(t) = z + t*d`` is inside the box for
181
+ for ``ta <= t <= tb``.
182
+ intersect : bool
183
+ When ``True``, there is a intersection between the line (or segment)
184
+ and the rectangular box. On the other hand, when ``False``, there is no
185
+ intersection.
186
+ """
187
+ # Make sure it is a numpy array
188
+ z = np.asarray(z)
189
+ d = np.asarray(d)
190
+ lb = np.asarray(lb)
191
+ ub = np.asarray(ub)
192
+ # Special case when d=0
193
+ if norm(d) == 0:
194
+ return 0, 0, False
195
+
196
+ # Get values for which d==0
197
+ zero_d = (d == 0)
198
+ # If the boundaries are not satisfied for some coordinate
199
+ # for which "d" is zero, there is no box-line intersection.
200
+ if (z[zero_d] < lb[zero_d]).any() or (z[zero_d] > ub[zero_d]).any():
201
+ intersect = False
202
+ return 0, 0, intersect
203
+ # Remove values for which d is zero
204
+ not_zero_d = np.logical_not(zero_d)
205
+ z = z[not_zero_d]
206
+ d = d[not_zero_d]
207
+ lb = lb[not_zero_d]
208
+ ub = ub[not_zero_d]
209
+
210
+ # Find a series of intervals (t_lb[i], t_ub[i]).
211
+ t_lb = (lb-z) / d
212
+ t_ub = (ub-z) / d
213
+ # Get the intersection of all those intervals.
214
+ ta = max(np.minimum(t_lb, t_ub))
215
+ tb = min(np.maximum(t_lb, t_ub))
216
+
217
+ # Check if intersection is feasible
218
+ if ta <= tb:
219
+ intersect = True
220
+ else:
221
+ intersect = False
222
+ # Checks to see if intersection happens within vectors length.
223
+ if not entire_line:
224
+ if tb < 0 or ta > 1:
225
+ intersect = False
226
+ ta = 0
227
+ tb = 0
228
+ else:
229
+ # Restrict intersection interval between 0 and 1.
230
+ ta = max(0, ta)
231
+ tb = min(1, tb)
232
+
233
+ return ta, tb, intersect
234
+
235
+
236
+ def box_sphere_intersections(z, d, lb, ub, trust_radius,
237
+ entire_line=False,
238
+ extra_info=False):
239
+ """Find the intersection between segment (or line) and box/sphere constraints.
240
+
241
+ Find the intersection between the segment (or line) defined by the
242
+ parametric equation ``x(t) = z + t*d``, the rectangular box
243
+ ``lb <= x <= ub`` and the ball ``||x|| <= trust_radius``.
244
+
245
+ Parameters
246
+ ----------
247
+ z : array_like, shape (n,)
248
+ Initial point.
249
+ d : array_like, shape (n,)
250
+ Direction.
251
+ lb : array_like, shape (n,)
252
+ Lower bounds to each one of the components of ``x``. Used
253
+ to delimit the rectangular box.
254
+ ub : array_like, shape (n, )
255
+ Upper bounds to each one of the components of ``x``. Used
256
+ to delimit the rectangular box.
257
+ trust_radius : float
258
+ Ball radius.
259
+ entire_line : bool, optional
260
+ When ``True``, the function returns the intersection between the line
261
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the constraints.
262
+ When ``False``, the function returns the intersection between the segment
263
+ ``x(t) = z + t*d``, ``0 <= t <= 1`` and the constraints.
264
+ extra_info : bool, optional
265
+ When ``True``, the function returns ``intersect_sphere`` and ``intersect_box``.
266
+
267
+ Returns
268
+ -------
269
+ ta, tb : float
270
+ The line/segment ``x(t) = z + t*d`` is inside the rectangular box and
271
+ inside the ball for ``ta <= t <= tb``.
272
+ intersect : bool
273
+ When ``True``, there is a intersection between the line (or segment)
274
+ and both constraints. On the other hand, when ``False``, there is no
275
+ intersection.
276
+ sphere_info : dict, optional
277
+ Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]``
278
+ for which the line intercepts the ball. And a boolean value indicating
279
+ whether the sphere is intersected by the line.
280
+ box_info : dict, optional
281
+ Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]``
282
+ for which the line intercepts the box. And a boolean value indicating
283
+ whether the box is intersected by the line.
284
+ """
285
+ ta_b, tb_b, intersect_b = box_intersections(z, d, lb, ub,
286
+ entire_line)
287
+ ta_s, tb_s, intersect_s = sphere_intersections(z, d,
288
+ trust_radius,
289
+ entire_line)
290
+ ta = np.maximum(ta_b, ta_s)
291
+ tb = np.minimum(tb_b, tb_s)
292
+ if intersect_b and intersect_s and ta <= tb:
293
+ intersect = True
294
+ else:
295
+ intersect = False
296
+
297
+ if extra_info:
298
+ sphere_info = {'ta': ta_s, 'tb': tb_s, 'intersect': intersect_s}
299
+ box_info = {'ta': ta_b, 'tb': tb_b, 'intersect': intersect_b}
300
+ return ta, tb, intersect, sphere_info, box_info
301
+ else:
302
+ return ta, tb, intersect
303
+
304
+
305
+ def inside_box_boundaries(x, lb, ub):
306
+ """Check if lb <= x <= ub."""
307
+ return (lb <= x).all() and (x <= ub).all()
308
+
309
+
310
+ def reinforce_box_boundaries(x, lb, ub):
311
+ """Return clipped value of x"""
312
+ return np.minimum(np.maximum(x, lb), ub)
313
+
314
+
315
+ def modified_dogleg(A, Y, b, trust_radius, lb, ub):
316
+ """Approximately minimize ``1/2*|| A x + b ||^2`` inside trust-region.
317
+
318
+ Approximately solve the problem of minimizing ``1/2*|| A x + b ||^2``
319
+ subject to ``||x|| < Delta`` and ``lb <= x <= ub`` using a modification
320
+ of the classical dogleg approach.
321
+
322
+ Parameters
323
+ ----------
324
+ A : LinearOperator (or sparse matrix or ndarray), shape (m, n)
325
+ Matrix ``A`` in the minimization problem. It should have
326
+ dimension ``(m, n)`` such that ``m < n``.
327
+ Y : LinearOperator (or sparse matrix or ndarray), shape (n, m)
328
+ LinearOperator that apply the projection matrix
329
+ ``Q = A.T inv(A A.T)`` to the vector. The obtained vector
330
+ ``y = Q x`` being the minimum norm solution of ``A y = x``.
331
+ b : array_like, shape (m,)
332
+ Vector ``b``in the minimization problem.
333
+ trust_radius: float
334
+ Trust radius to be considered. Delimits a sphere boundary
335
+ to the problem.
336
+ lb : array_like, shape (n,)
337
+ Lower bounds to each one of the components of ``x``.
338
+ It is expected that ``lb <= 0``, otherwise the algorithm
339
+ may fail. If ``lb[i] = -Inf``, the lower
340
+ bound for the ith component is just ignored.
341
+ ub : array_like, shape (n, )
342
+ Upper bounds to each one of the components of ``x``.
343
+ It is expected that ``ub >= 0``, otherwise the algorithm
344
+ may fail. If ``ub[i] = Inf``, the upper bound for the ith
345
+ component is just ignored.
346
+
347
+ Returns
348
+ -------
349
+ x : array_like, shape (n,)
350
+ Solution to the problem.
351
+
352
+ Notes
353
+ -----
354
+ Based on implementations described in pp. 885-886 from [1]_.
355
+
356
+ References
357
+ ----------
358
+ .. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal.
359
+ "An interior point algorithm for large-scale nonlinear
360
+ programming." SIAM Journal on Optimization 9.4 (1999): 877-900.
361
+ """
362
+ # Compute minimum norm minimizer of 1/2*|| A x + b ||^2.
363
+ newton_point = -Y.dot(b)
364
+ # Check for interior point
365
+ if inside_box_boundaries(newton_point, lb, ub) \
366
+ and norm(newton_point) <= trust_radius:
367
+ x = newton_point
368
+ return x
369
+
370
+ # Compute gradient vector ``g = A.T b``
371
+ g = A.T.dot(b)
372
+ # Compute Cauchy point
373
+ # `cauchy_point = g.T g / (g.T A.T A g)``.
374
+ A_g = A.dot(g)
375
+ cauchy_point = -np.dot(g, g) / np.dot(A_g, A_g) * g
376
+ # Origin
377
+ origin_point = np.zeros_like(cauchy_point)
378
+
379
+ # Check the segment between cauchy_point and newton_point
380
+ # for a possible solution.
381
+ z = cauchy_point
382
+ p = newton_point - cauchy_point
383
+ _, alpha, intersect = box_sphere_intersections(z, p, lb, ub,
384
+ trust_radius)
385
+ if intersect:
386
+ x1 = z + alpha*p
387
+ else:
388
+ # Check the segment between the origin and cauchy_point
389
+ # for a possible solution.
390
+ z = origin_point
391
+ p = cauchy_point
392
+ _, alpha, _ = box_sphere_intersections(z, p, lb, ub,
393
+ trust_radius)
394
+ x1 = z + alpha*p
395
+
396
+ # Check the segment between origin and newton_point
397
+ # for a possible solution.
398
+ z = origin_point
399
+ p = newton_point
400
+ _, alpha, _ = box_sphere_intersections(z, p, lb, ub,
401
+ trust_radius)
402
+ x2 = z + alpha*p
403
+
404
+ # Return the best solution among x1 and x2.
405
+ if norm(A.dot(x1) + b) < norm(A.dot(x2) + b):
406
+ return x1
407
+ else:
408
+ return x2
409
+
410
+
411
+ def projected_cg(H, c, Z, Y, b, trust_radius=np.inf,
412
+ lb=None, ub=None, tol=None,
413
+ max_iter=None, max_infeasible_iter=None,
414
+ return_all=False):
415
+ """Solve EQP problem with projected CG method.
416
+
417
+ Solve equality-constrained quadratic programming problem
418
+ ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` and,
419
+ possibly, to trust region constraints ``||x|| < trust_radius``
420
+ and box constraints ``lb <= x <= ub``.
421
+
422
+ Parameters
423
+ ----------
424
+ H : LinearOperator (or sparse matrix or ndarray), shape (n, n)
425
+ Operator for computing ``H v``.
426
+ c : array_like, shape (n,)
427
+ Gradient of the quadratic objective function.
428
+ Z : LinearOperator (or sparse matrix or ndarray), shape (n, n)
429
+ Operator for projecting ``x`` into the null space of A.
430
+ Y : LinearOperator, sparse matrix, ndarray, shape (n, m)
431
+ Operator that, for a given a vector ``b``, compute smallest
432
+ norm solution of ``A x + b = 0``.
433
+ b : array_like, shape (m,)
434
+ Right-hand side of the constraint equation.
435
+ trust_radius : float, optional
436
+ Trust radius to be considered. By default, uses ``trust_radius=inf``,
437
+ which means no trust radius at all.
438
+ lb : array_like, shape (n,), optional
439
+ Lower bounds to each one of the components of ``x``.
440
+ If ``lb[i] = -Inf`` the lower bound for the i-th
441
+ component is just ignored (default).
442
+ ub : array_like, shape (n, ), optional
443
+ Upper bounds to each one of the components of ``x``.
444
+ If ``ub[i] = Inf`` the upper bound for the i-th
445
+ component is just ignored (default).
446
+ tol : float, optional
447
+ Tolerance used to interrupt the algorithm.
448
+ max_iter : int, optional
449
+ Maximum algorithm iterations. Where ``max_inter <= n-m``.
450
+ By default, uses ``max_iter = n-m``.
451
+ max_infeasible_iter : int, optional
452
+ Maximum infeasible (regarding box constraints) iterations the
453
+ algorithm is allowed to take.
454
+ By default, uses ``max_infeasible_iter = n-m``.
455
+ return_all : bool, optional
456
+ When ``true``, return the list of all vectors through the iterations.
457
+
458
+ Returns
459
+ -------
460
+ x : array_like, shape (n,)
461
+ Solution of the EQP problem.
462
+ info : Dict
463
+ Dictionary containing the following:
464
+
465
+ - niter : Number of iterations.
466
+ - stop_cond : Reason for algorithm termination:
467
+ 1. Iteration limit was reached;
468
+ 2. Reached the trust-region boundary;
469
+ 3. Negative curvature detected;
470
+ 4. Tolerance was satisfied.
471
+ - allvecs : List containing all intermediary vectors (optional).
472
+ - hits_boundary : True if the proposed step is on the boundary
473
+ of the trust region.
474
+
475
+ Notes
476
+ -----
477
+ Implementation of Algorithm 6.2 on [1]_.
478
+
479
+ In the absence of spherical and box constraints, for sufficient
480
+ iterations, the method returns a truly optimal result.
481
+ In the presence of those constraints, the value returned is only
482
+ a inexpensive approximation of the optimal value.
483
+
484
+ References
485
+ ----------
486
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
487
+ "On the solution of equality constrained quadratic
488
+ programming problems arising in optimization."
489
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
490
+ """
491
+ CLOSE_TO_ZERO = 1e-25
492
+
493
+ n, = np.shape(c) # Number of parameters
494
+ m, = np.shape(b) # Number of constraints
495
+
496
+ # Initial Values
497
+ x = Y.dot(-b)
498
+ r = Z.dot(H.dot(x) + c)
499
+ g = Z.dot(r)
500
+ p = -g
501
+
502
+ # Store ``x`` value
503
+ if return_all:
504
+ allvecs = [x]
505
+ # Values for the first iteration
506
+ H_p = H.dot(p)
507
+ rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389)
508
+
509
+ # If x > trust-region the problem does not have a solution.
510
+ tr_distance = trust_radius - norm(x)
511
+ if tr_distance < 0:
512
+ raise ValueError("Trust region problem does not have a solution.")
513
+ # If x == trust_radius, then x is the solution
514
+ # to the optimization problem, since x is the
515
+ # minimum norm solution to Ax=b.
516
+ elif tr_distance < CLOSE_TO_ZERO:
517
+ info = {'niter': 0, 'stop_cond': 2, 'hits_boundary': True}
518
+ if return_all:
519
+ allvecs.append(x)
520
+ info['allvecs'] = allvecs
521
+ return x, info
522
+
523
+ # Set default tolerance
524
+ if tol is None:
525
+ tol = max(min(0.01 * np.sqrt(rt_g), 0.1 * rt_g), CLOSE_TO_ZERO)
526
+ # Set default lower and upper bounds
527
+ if lb is None:
528
+ lb = np.full(n, -np.inf)
529
+ if ub is None:
530
+ ub = np.full(n, np.inf)
531
+ # Set maximum iterations
532
+ if max_iter is None:
533
+ max_iter = n-m
534
+ max_iter = min(max_iter, n-m)
535
+ # Set maximum infeasible iterations
536
+ if max_infeasible_iter is None:
537
+ max_infeasible_iter = n-m
538
+
539
+ hits_boundary = False
540
+ stop_cond = 1
541
+ counter = 0
542
+ last_feasible_x = np.zeros_like(x)
543
+ k = 0
544
+ for i in range(max_iter):
545
+ # Stop criteria - Tolerance : r.T g < tol
546
+ if rt_g < tol:
547
+ stop_cond = 4
548
+ break
549
+ k += 1
550
+ # Compute curvature
551
+ pt_H_p = H_p.dot(p)
552
+ # Stop criteria - Negative curvature
553
+ if pt_H_p <= 0:
554
+ if np.isinf(trust_radius):
555
+ raise ValueError("Negative curvature not allowed "
556
+ "for unrestricted problems.")
557
+ else:
558
+ # Find intersection with constraints
559
+ _, alpha, intersect = box_sphere_intersections(
560
+ x, p, lb, ub, trust_radius, entire_line=True)
561
+ # Update solution
562
+ if intersect:
563
+ x = x + alpha*p
564
+ # Reinforce variables are inside box constraints.
565
+ # This is only necessary because of roundoff errors.
566
+ x = reinforce_box_boundaries(x, lb, ub)
567
+ # Attribute information
568
+ stop_cond = 3
569
+ hits_boundary = True
570
+ break
571
+
572
+ # Get next step
573
+ alpha = rt_g / pt_H_p
574
+ x_next = x + alpha*p
575
+
576
+ # Stop criteria - Hits boundary
577
+ if np.linalg.norm(x_next) >= trust_radius:
578
+ # Find intersection with box constraints
579
+ _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub,
580
+ trust_radius)
581
+ # Update solution
582
+ if intersect:
583
+ x = x + theta*alpha*p
584
+ # Reinforce variables are inside box constraints.
585
+ # This is only necessary because of roundoff errors.
586
+ x = reinforce_box_boundaries(x, lb, ub)
587
+ # Attribute information
588
+ stop_cond = 2
589
+ hits_boundary = True
590
+ break
591
+
592
+ # Check if ``x`` is inside the box and start counter if it is not.
593
+ if inside_box_boundaries(x_next, lb, ub):
594
+ counter = 0
595
+ else:
596
+ counter += 1
597
+ # Whenever outside box constraints keep looking for intersections.
598
+ if counter > 0:
599
+ _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub,
600
+ trust_radius)
601
+ if intersect:
602
+ last_feasible_x = x + theta*alpha*p
603
+ # Reinforce variables are inside box constraints.
604
+ # This is only necessary because of roundoff errors.
605
+ last_feasible_x = reinforce_box_boundaries(last_feasible_x,
606
+ lb, ub)
607
+ counter = 0
608
+ # Stop after too many infeasible (regarding box constraints) iteration.
609
+ if counter > max_infeasible_iter:
610
+ break
611
+ # Store ``x_next`` value
612
+ if return_all:
613
+ allvecs.append(x_next)
614
+
615
+ # Update residual
616
+ r_next = r + alpha*H_p
617
+ # Project residual g+ = Z r+
618
+ g_next = Z.dot(r_next)
619
+ # Compute conjugate direction step d
620
+ rt_g_next = norm(g_next)**2 # g.T g = r.T g (ref [1]_ p.1389)
621
+ beta = rt_g_next / rt_g
622
+ p = - g_next + beta*p
623
+ # Prepare for next iteration
624
+ x = x_next
625
+ g = g_next
626
+ r = g_next
627
+ rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389)
628
+ H_p = H.dot(p)
629
+
630
+ if not inside_box_boundaries(x, lb, ub):
631
+ x = last_feasible_x
632
+ hits_boundary = True
633
+ info = {'niter': k, 'stop_cond': stop_cond,
634
+ 'hits_boundary': hits_boundary}
635
+ if return_all:
636
+ info['allvecs'] = allvecs
637
+ return x, info
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/report.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Progress report printers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ class ReportBase:
6
+ COLUMN_NAMES: list[str] = NotImplemented
7
+ COLUMN_WIDTHS: list[int] = NotImplemented
8
+ ITERATION_FORMATS: list[str] = NotImplemented
9
+
10
+ @classmethod
11
+ def print_header(cls):
12
+ fmt = ("|"
13
+ + "|".join([f"{{:^{x}}}" for x in cls.COLUMN_WIDTHS])
14
+ + "|")
15
+ separators = ['-' * x for x in cls.COLUMN_WIDTHS]
16
+ print(fmt.format(*cls.COLUMN_NAMES))
17
+ print(fmt.format(*separators))
18
+
19
+ @classmethod
20
+ def print_iteration(cls, *args):
21
+ iteration_format = [f"{{:{x}}}" for x in cls.ITERATION_FORMATS]
22
+ fmt = "|" + "|".join(iteration_format) + "|"
23
+ print(fmt.format(*args))
24
+
25
+ @classmethod
26
+ def print_footer(cls):
27
+ print()
28
+
29
+
30
+ class BasicReport(ReportBase):
31
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
32
+ "opt", "c viol"]
33
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10]
34
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e",
35
+ "^10.2e", "^10.2e", "^10.2e"]
36
+
37
+
38
+ class SQPReport(ReportBase):
39
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
40
+ "opt", "c viol", "penalty", "CG stop"]
41
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 7]
42
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e",
43
+ "^10.2e", "^10.2e", "^7"]
44
+
45
+
46
+ class IPReport(ReportBase):
47
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
48
+ "opt", "c viol", "penalty", "barrier param", "CG stop"]
49
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 13, 7]
50
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e",
51
+ "^10.2e", "^10.2e", "^13.2e", "^7"]
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py ADDED
File without changes
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-310.pyc ADDED
Binary file (6.55 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_array_equal, assert_equal
3
+ from scipy.optimize._constraints import (NonlinearConstraint, Bounds,
4
+ PreparedConstraint)
5
+ from scipy.optimize._trustregion_constr.canonical_constraint \
6
+ import CanonicalConstraint, initial_constraints_as_canonical
7
+
8
+
9
+ def create_quadratic_function(n, m, rng):
10
+ a = rng.rand(m)
11
+ A = rng.rand(m, n)
12
+ H = rng.rand(m, n, n)
13
+ HT = np.transpose(H, (1, 2, 0))
14
+
15
+ def fun(x):
16
+ return a + A.dot(x) + 0.5 * H.dot(x).dot(x)
17
+
18
+ def jac(x):
19
+ return A + H.dot(x)
20
+
21
+ def hess(x, v):
22
+ return HT.dot(v)
23
+
24
+ return fun, jac, hess
25
+
26
+
27
+ def test_bounds_cases():
28
+ # Test 1: no constraints.
29
+ user_constraint = Bounds(-np.inf, np.inf)
30
+ x0 = np.array([-1, 2])
31
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
32
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
33
+
34
+ assert_equal(c.n_eq, 0)
35
+ assert_equal(c.n_ineq, 0)
36
+
37
+ c_eq, c_ineq = c.fun(x0)
38
+ assert_array_equal(c_eq, [])
39
+ assert_array_equal(c_ineq, [])
40
+
41
+ J_eq, J_ineq = c.jac(x0)
42
+ assert_array_equal(J_eq, np.empty((0, 2)))
43
+ assert_array_equal(J_ineq, np.empty((0, 2)))
44
+
45
+ assert_array_equal(c.keep_feasible, [])
46
+
47
+ # Test 2: infinite lower bound.
48
+ user_constraint = Bounds(-np.inf, [0, np.inf, 1], [False, True, True])
49
+ x0 = np.array([-1, -2, -3], dtype=float)
50
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
51
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
52
+
53
+ assert_equal(c.n_eq, 0)
54
+ assert_equal(c.n_ineq, 2)
55
+
56
+ c_eq, c_ineq = c.fun(x0)
57
+ assert_array_equal(c_eq, [])
58
+ assert_array_equal(c_ineq, [-1, -4])
59
+
60
+ J_eq, J_ineq = c.jac(x0)
61
+ assert_array_equal(J_eq, np.empty((0, 3)))
62
+ assert_array_equal(J_ineq, np.array([[1, 0, 0], [0, 0, 1]]))
63
+
64
+ assert_array_equal(c.keep_feasible, [False, True])
65
+
66
+ # Test 3: infinite upper bound.
67
+ user_constraint = Bounds([0, 1, -np.inf], np.inf, [True, False, True])
68
+ x0 = np.array([1, 2, 3], dtype=float)
69
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
70
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
71
+
72
+ assert_equal(c.n_eq, 0)
73
+ assert_equal(c.n_ineq, 2)
74
+
75
+ c_eq, c_ineq = c.fun(x0)
76
+ assert_array_equal(c_eq, [])
77
+ assert_array_equal(c_ineq, [-1, -1])
78
+
79
+ J_eq, J_ineq = c.jac(x0)
80
+ assert_array_equal(J_eq, np.empty((0, 3)))
81
+ assert_array_equal(J_ineq, np.array([[-1, 0, 0], [0, -1, 0]]))
82
+
83
+ assert_array_equal(c.keep_feasible, [True, False])
84
+
85
+ # Test 4: interval constraint.
86
+ user_constraint = Bounds([-1, -np.inf, 2, 3], [1, np.inf, 10, 3],
87
+ [False, True, True, True])
88
+ x0 = np.array([0, 10, 8, 5])
89
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
90
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
91
+
92
+ assert_equal(c.n_eq, 1)
93
+ assert_equal(c.n_ineq, 4)
94
+
95
+ c_eq, c_ineq = c.fun(x0)
96
+ assert_array_equal(c_eq, [2])
97
+ assert_array_equal(c_ineq, [-1, -2, -1, -6])
98
+
99
+ J_eq, J_ineq = c.jac(x0)
100
+ assert_array_equal(J_eq, [[0, 0, 0, 1]])
101
+ assert_array_equal(J_ineq, [[1, 0, 0, 0],
102
+ [0, 0, 1, 0],
103
+ [-1, 0, 0, 0],
104
+ [0, 0, -1, 0]])
105
+
106
+ assert_array_equal(c.keep_feasible, [False, True, False, True])
107
+
108
+
109
+ def test_nonlinear_constraint():
110
+ n = 3
111
+ m = 5
112
+ rng = np.random.RandomState(0)
113
+ x0 = rng.rand(n)
114
+
115
+ fun, jac, hess = create_quadratic_function(n, m, rng)
116
+ f = fun(x0)
117
+ J = jac(x0)
118
+
119
+ lb = [-10, 3, -np.inf, -np.inf, -5]
120
+ ub = [10, 3, np.inf, 3, np.inf]
121
+ user_constraint = NonlinearConstraint(
122
+ fun, lb, ub, jac, hess, [True, False, False, True, False])
123
+
124
+ for sparse_jacobian in [False, True]:
125
+ prepared_constraint = PreparedConstraint(user_constraint, x0,
126
+ sparse_jacobian)
127
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
128
+
129
+ assert_array_equal(c.n_eq, 1)
130
+ assert_array_equal(c.n_ineq, 4)
131
+
132
+ c_eq, c_ineq = c.fun(x0)
133
+ assert_array_equal(c_eq, [f[1] - lb[1]])
134
+ assert_array_equal(c_ineq, [f[3] - ub[3], lb[4] - f[4],
135
+ f[0] - ub[0], lb[0] - f[0]])
136
+
137
+ J_eq, J_ineq = c.jac(x0)
138
+ if sparse_jacobian:
139
+ J_eq = J_eq.toarray()
140
+ J_ineq = J_ineq.toarray()
141
+
142
+ assert_array_equal(J_eq, J[1, None])
143
+ assert_array_equal(J_ineq, np.vstack((J[3], -J[4], J[0], -J[0])))
144
+
145
+ v_eq = rng.rand(c.n_eq)
146
+ v_ineq = rng.rand(c.n_ineq)
147
+ v = np.zeros(m)
148
+ v[1] = v_eq[0]
149
+ v[3] = v_ineq[0]
150
+ v[4] = -v_ineq[1]
151
+ v[0] = v_ineq[2] - v_ineq[3]
152
+ assert_array_equal(c.hess(x0, v_eq, v_ineq), hess(x0, v))
153
+
154
+ assert_array_equal(c.keep_feasible, [True, False, True, True])
155
+
156
+
157
+ def test_concatenation():
158
+ rng = np.random.RandomState(0)
159
+ n = 4
160
+ x0 = rng.rand(n)
161
+
162
+ f1 = x0
163
+ J1 = np.eye(n)
164
+ lb1 = [-1, -np.inf, -2, 3]
165
+ ub1 = [1, np.inf, np.inf, 3]
166
+ bounds = Bounds(lb1, ub1, [False, False, True, False])
167
+
168
+ fun, jac, hess = create_quadratic_function(n, 5, rng)
169
+ f2 = fun(x0)
170
+ J2 = jac(x0)
171
+ lb2 = [-10, 3, -np.inf, -np.inf, -5]
172
+ ub2 = [10, 3, np.inf, 5, np.inf]
173
+ nonlinear = NonlinearConstraint(
174
+ fun, lb2, ub2, jac, hess, [True, False, False, True, False])
175
+
176
+ for sparse_jacobian in [False, True]:
177
+ bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian)
178
+ nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian)
179
+
180
+ c1 = CanonicalConstraint.from_PreparedConstraint(bounds_prepared)
181
+ c2 = CanonicalConstraint.from_PreparedConstraint(nonlinear_prepared)
182
+ c = CanonicalConstraint.concatenate([c1, c2], sparse_jacobian)
183
+
184
+ assert_equal(c.n_eq, 2)
185
+ assert_equal(c.n_ineq, 7)
186
+
187
+ c_eq, c_ineq = c.fun(x0)
188
+ assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]])
189
+ assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0],
190
+ lb1[0] - f1[0], f2[3] - ub2[3],
191
+ lb2[4] - f2[4], f2[0] - ub2[0],
192
+ lb2[0] - f2[0]])
193
+
194
+ J_eq, J_ineq = c.jac(x0)
195
+ if sparse_jacobian:
196
+ J_eq = J_eq.toarray()
197
+ J_ineq = J_ineq.toarray()
198
+
199
+ assert_array_equal(J_eq, np.vstack((J1[3], J2[1])))
200
+ assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3],
201
+ -J2[4], J2[0], -J2[0])))
202
+
203
+ v_eq = rng.rand(c.n_eq)
204
+ v_ineq = rng.rand(c.n_ineq)
205
+ v = np.zeros(5)
206
+ v[1] = v_eq[1]
207
+ v[3] = v_ineq[3]
208
+ v[4] = -v_ineq[4]
209
+ v[0] = v_ineq[5] - v_ineq[6]
210
+ H = c.hess(x0, v_eq, v_ineq).dot(np.eye(n))
211
+ assert_array_equal(H, hess(x0, v))
212
+
213
+ assert_array_equal(c.keep_feasible,
214
+ [True, False, False, True, False, True, True])
215
+
216
+
217
+ def test_empty():
218
+ x = np.array([1, 2, 3])
219
+ c = CanonicalConstraint.empty(3)
220
+ assert_equal(c.n_eq, 0)
221
+ assert_equal(c.n_ineq, 0)
222
+
223
+ c_eq, c_ineq = c.fun(x)
224
+ assert_array_equal(c_eq, [])
225
+ assert_array_equal(c_ineq, [])
226
+
227
+ J_eq, J_ineq = c.jac(x)
228
+ assert_array_equal(J_eq, np.empty((0, 3)))
229
+ assert_array_equal(J_ineq, np.empty((0, 3)))
230
+
231
+ H = c.hess(x, None, None).toarray()
232
+ assert_array_equal(H, np.zeros((3, 3)))
233
+
234
+
235
+ def test_initial_constraints_as_canonical():
236
+ # rng is only used to generate the coefficients of the quadratic
237
+ # function that is used by the nonlinear constraint.
238
+ rng = np.random.RandomState(0)
239
+
240
+ x0 = np.array([0.5, 0.4, 0.3, 0.2])
241
+ n = len(x0)
242
+
243
+ lb1 = [-1, -np.inf, -2, 3]
244
+ ub1 = [1, np.inf, np.inf, 3]
245
+ bounds = Bounds(lb1, ub1, [False, False, True, False])
246
+
247
+ fun, jac, hess = create_quadratic_function(n, 5, rng)
248
+ lb2 = [-10, 3, -np.inf, -np.inf, -5]
249
+ ub2 = [10, 3, np.inf, 5, np.inf]
250
+ nonlinear = NonlinearConstraint(
251
+ fun, lb2, ub2, jac, hess, [True, False, False, True, False])
252
+
253
+ for sparse_jacobian in [False, True]:
254
+ bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian)
255
+ nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian)
256
+
257
+ f1 = bounds_prepared.fun.f
258
+ J1 = bounds_prepared.fun.J
259
+ f2 = nonlinear_prepared.fun.f
260
+ J2 = nonlinear_prepared.fun.J
261
+
262
+ c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical(
263
+ n, [bounds_prepared, nonlinear_prepared], sparse_jacobian)
264
+
265
+ assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]])
266
+ assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0],
267
+ lb1[0] - f1[0], f2[3] - ub2[3],
268
+ lb2[4] - f2[4], f2[0] - ub2[0],
269
+ lb2[0] - f2[0]])
270
+
271
+ if sparse_jacobian:
272
+ J1 = J1.toarray()
273
+ J2 = J2.toarray()
274
+ J_eq = J_eq.toarray()
275
+ J_ineq = J_ineq.toarray()
276
+
277
+ assert_array_equal(J_eq, np.vstack((J1[3], J2[1])))
278
+ assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3],
279
+ -J2[4], J2[0], -J2[0])))
280
+
281
+
282
+ def test_initial_constraints_as_canonical_empty():
283
+ n = 3
284
+ for sparse_jacobian in [False, True]:
285
+ c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical(
286
+ n, [], sparse_jacobian)
287
+
288
+ assert_array_equal(c_eq, [])
289
+ assert_array_equal(c_ineq, [])
290
+
291
+ if sparse_jacobian:
292
+ J_eq = J_eq.toarray()
293
+ J_ineq = J_ineq.toarray()
294
+
295
+ assert_array_equal(J_eq, np.empty((0, n)))
296
+ assert_array_equal(J_ineq, np.empty((0, n)))
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import scipy.linalg
3
+ from scipy.sparse import csc_matrix
4
+ from scipy.optimize._trustregion_constr.projections \
5
+ import projections, orthogonality
6
+ from numpy.testing import (TestCase, assert_array_almost_equal,
7
+ assert_equal, assert_allclose)
8
+
9
+ try:
10
+ from sksparse.cholmod import cholesky_AAt # noqa: F401
11
+ sksparse_available = True
12
+ available_sparse_methods = ("NormalEquation", "AugmentedSystem")
13
+ except ImportError:
14
+ sksparse_available = False
15
+ available_sparse_methods = ("AugmentedSystem",)
16
+ available_dense_methods = ('QRFactorization', 'SVDFactorization')
17
+
18
+
19
+ class TestProjections(TestCase):
20
+
21
+ def test_nullspace_and_least_squares_sparse(self):
22
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
23
+ [0, 8, 7, 0, 1, 5, 9, 0],
24
+ [1, 0, 0, 0, 0, 1, 2, 3]])
25
+ At_dense = A_dense.T
26
+ A = csc_matrix(A_dense)
27
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
28
+ [1, 10, 3, 0, 1, 6, 7, 8],
29
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8])
30
+
31
+ for method in available_sparse_methods:
32
+ Z, LS, _ = projections(A, method)
33
+ for z in test_points:
34
+ # Test if x is in the null_space
35
+ x = Z.matvec(z)
36
+ assert_array_almost_equal(A.dot(x), 0)
37
+ # Test orthogonality
38
+ assert_array_almost_equal(orthogonality(A, x), 0)
39
+ # Test if x is the least square solution
40
+ x = LS.matvec(z)
41
+ x2 = scipy.linalg.lstsq(At_dense, z)[0]
42
+ assert_array_almost_equal(x, x2)
43
+
44
+ def test_iterative_refinements_sparse(self):
45
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
46
+ [0, 8, 7, 0, 1, 5, 9, 0],
47
+ [1, 0, 0, 0, 0, 1, 2, 3]])
48
+ A = csc_matrix(A_dense)
49
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
50
+ [1, 10, 3, 0, 1, 6, 7, 8],
51
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8],
52
+ [1, 0, 0, 0, 0, 1, 2, 3+1e-10])
53
+
54
+ for method in available_sparse_methods:
55
+ Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=100)
56
+ for z in test_points:
57
+ # Test if x is in the null_space
58
+ x = Z.matvec(z)
59
+ atol = 1e-13 * abs(x).max()
60
+ assert_allclose(A.dot(x), 0, atol=atol)
61
+ # Test orthogonality
62
+ assert_allclose(orthogonality(A, x), 0, atol=1e-13)
63
+
64
+ def test_rowspace_sparse(self):
65
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
66
+ [0, 8, 7, 0, 1, 5, 9, 0],
67
+ [1, 0, 0, 0, 0, 1, 2, 3]])
68
+ A = csc_matrix(A_dense)
69
+ test_points = ([1, 2, 3],
70
+ [1, 10, 3],
71
+ [1.12, 10, 0])
72
+
73
+ for method in available_sparse_methods:
74
+ _, _, Y = projections(A, method)
75
+ for z in test_points:
76
+ # Test if x is solution of A x = z
77
+ x = Y.matvec(z)
78
+ assert_array_almost_equal(A.dot(x), z)
79
+ # Test if x is in the return row space of A
80
+ A_ext = np.vstack((A_dense, x))
81
+ assert_equal(np.linalg.matrix_rank(A_dense),
82
+ np.linalg.matrix_rank(A_ext))
83
+
84
+ def test_nullspace_and_least_squares_dense(self):
85
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
86
+ [0, 8, 7, 0, 1, 5, 9, 0],
87
+ [1, 0, 0, 0, 0, 1, 2, 3]])
88
+ At = A.T
89
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
90
+ [1, 10, 3, 0, 1, 6, 7, 8],
91
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8])
92
+
93
+ for method in available_dense_methods:
94
+ Z, LS, _ = projections(A, method)
95
+ for z in test_points:
96
+ # Test if x is in the null_space
97
+ x = Z.matvec(z)
98
+ assert_array_almost_equal(A.dot(x), 0)
99
+ # Test orthogonality
100
+ assert_array_almost_equal(orthogonality(A, x), 0)
101
+ # Test if x is the least square solution
102
+ x = LS.matvec(z)
103
+ x2 = scipy.linalg.lstsq(At, z)[0]
104
+ assert_array_almost_equal(x, x2)
105
+
106
+ def test_compare_dense_and_sparse(self):
107
+ D = np.diag(range(1, 101))
108
+ A = np.hstack([D, D, D, D])
109
+ A_sparse = csc_matrix(A)
110
+ np.random.seed(0)
111
+
112
+ Z, LS, Y = projections(A)
113
+ Z_sparse, LS_sparse, Y_sparse = projections(A_sparse)
114
+ for k in range(20):
115
+ z = np.random.normal(size=(400,))
116
+ assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z))
117
+ assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z))
118
+ x = np.random.normal(size=(100,))
119
+ assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x))
120
+
121
+ def test_compare_dense_and_sparse2(self):
122
+ D1 = np.diag([-1.7, 1, 0.5])
123
+ D2 = np.diag([1, -0.6, -0.3])
124
+ D3 = np.diag([-0.3, -1.5, 2])
125
+ A = np.hstack([D1, D2, D3])
126
+ A_sparse = csc_matrix(A)
127
+ np.random.seed(0)
128
+
129
+ Z, LS, Y = projections(A)
130
+ Z_sparse, LS_sparse, Y_sparse = projections(A_sparse)
131
+ for k in range(1):
132
+ z = np.random.normal(size=(9,))
133
+ assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z))
134
+ assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z))
135
+ x = np.random.normal(size=(3,))
136
+ assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x))
137
+
138
+ def test_iterative_refinements_dense(self):
139
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
140
+ [0, 8, 7, 0, 1, 5, 9, 0],
141
+ [1, 0, 0, 0, 0, 1, 2, 3]])
142
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
143
+ [1, 10, 3, 0, 1, 6, 7, 8],
144
+ [1, 0, 0, 0, 0, 1, 2, 3+1e-10])
145
+
146
+ for method in available_dense_methods:
147
+ Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=10)
148
+ for z in test_points:
149
+ # Test if x is in the null_space
150
+ x = Z.matvec(z)
151
+ assert_allclose(A.dot(x), 0, rtol=0, atol=2.5e-14)
152
+ # Test orthogonality
153
+ assert_allclose(orthogonality(A, x), 0, rtol=0, atol=5e-16)
154
+
155
+ def test_rowspace_dense(self):
156
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
157
+ [0, 8, 7, 0, 1, 5, 9, 0],
158
+ [1, 0, 0, 0, 0, 1, 2, 3]])
159
+ test_points = ([1, 2, 3],
160
+ [1, 10, 3],
161
+ [1.12, 10, 0])
162
+
163
+ for method in available_dense_methods:
164
+ _, _, Y = projections(A, method)
165
+ for z in test_points:
166
+ # Test if x is solution of A x = z
167
+ x = Y.matvec(z)
168
+ assert_array_almost_equal(A.dot(x), z)
169
+ # Test if x is in the return row space of A
170
+ A_ext = np.vstack((A, x))
171
+ assert_equal(np.linalg.matrix_rank(A),
172
+ np.linalg.matrix_rank(A_ext))
173
+
174
+
175
+ class TestOrthogonality(TestCase):
176
+
177
+ def test_dense_matrix(self):
178
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
179
+ [0, 8, 7, 0, 1, 5, 9, 0],
180
+ [1, 0, 0, 0, 0, 1, 2, 3]])
181
+ test_vectors = ([-1.98931144, -1.56363389,
182
+ -0.84115584, 2.2864762,
183
+ 5.599141, 0.09286976,
184
+ 1.37040802, -0.28145812],
185
+ [697.92794044, -4091.65114008,
186
+ -3327.42316335, 836.86906951,
187
+ 99434.98929065, -1285.37653682,
188
+ -4109.21503806, 2935.29289083])
189
+ test_expected_orth = (0, 0)
190
+
191
+ for i in range(len(test_vectors)):
192
+ x = test_vectors[i]
193
+ orth = test_expected_orth[i]
194
+ assert_array_almost_equal(orthogonality(A, x), orth)
195
+
196
+ def test_sparse_matrix(self):
197
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
198
+ [0, 8, 7, 0, 1, 5, 9, 0],
199
+ [1, 0, 0, 0, 0, 1, 2, 3]])
200
+ A = csc_matrix(A)
201
+ test_vectors = ([-1.98931144, -1.56363389,
202
+ -0.84115584, 2.2864762,
203
+ 5.599141, 0.09286976,
204
+ 1.37040802, -0.28145812],
205
+ [697.92794044, -4091.65114008,
206
+ -3327.42316335, 836.86906951,
207
+ 99434.98929065, -1285.37653682,
208
+ -4109.21503806, 2935.29289083])
209
+ test_expected_orth = (0, 0)
210
+
211
+ for i in range(len(test_vectors)):
212
+ x = test_vectors[i]
213
+ orth = test_expected_orth[i]
214
+ assert_array_almost_equal(orthogonality(A, x), orth)
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py ADDED
@@ -0,0 +1,645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.sparse import csc_matrix
3
+ from scipy.optimize._trustregion_constr.qp_subproblem \
4
+ import (eqp_kktfact,
5
+ projected_cg,
6
+ box_intersections,
7
+ sphere_intersections,
8
+ box_sphere_intersections,
9
+ modified_dogleg)
10
+ from scipy.optimize._trustregion_constr.projections \
11
+ import projections
12
+ from numpy.testing import TestCase, assert_array_almost_equal, assert_equal
13
+ import pytest
14
+
15
+
16
+ class TestEQPDirectFactorization(TestCase):
17
+
18
+ # From Example 16.2 Nocedal/Wright "Numerical
19
+ # Optimization" p.452.
20
+ def test_nocedal_example(self):
21
+ H = csc_matrix([[6, 2, 1],
22
+ [2, 5, 2],
23
+ [1, 2, 4]])
24
+ A = csc_matrix([[1, 0, 1],
25
+ [0, 1, 1]])
26
+ c = np.array([-8, -3, -3])
27
+ b = -np.array([3, 0])
28
+ x, lagrange_multipliers = eqp_kktfact(H, c, A, b)
29
+ assert_array_almost_equal(x, [2, -1, 1])
30
+ assert_array_almost_equal(lagrange_multipliers, [3, -2])
31
+
32
+
33
+ class TestSphericalBoundariesIntersections(TestCase):
34
+
35
+ def test_2d_sphere_constraints(self):
36
+ # Interior inicial point
37
+ ta, tb, intersect = sphere_intersections([0, 0],
38
+ [1, 0], 0.5)
39
+ assert_array_almost_equal([ta, tb], [0, 0.5])
40
+ assert_equal(intersect, True)
41
+
42
+ # No intersection between line and circle
43
+ ta, tb, intersect = sphere_intersections([2, 0],
44
+ [0, 1], 1)
45
+ assert_equal(intersect, False)
46
+
47
+ # Outside initial point pointing toward outside the circle
48
+ ta, tb, intersect = sphere_intersections([2, 0],
49
+ [1, 0], 1)
50
+ assert_equal(intersect, False)
51
+
52
+ # Outside initial point pointing toward inside the circle
53
+ ta, tb, intersect = sphere_intersections([2, 0],
54
+ [-1, 0], 1.5)
55
+ assert_array_almost_equal([ta, tb], [0.5, 1])
56
+ assert_equal(intersect, True)
57
+
58
+ # Initial point on the boundary
59
+ ta, tb, intersect = sphere_intersections([2, 0],
60
+ [1, 0], 2)
61
+ assert_array_almost_equal([ta, tb], [0, 0])
62
+ assert_equal(intersect, True)
63
+
64
+ def test_2d_sphere_constraints_line_intersections(self):
65
+ # Interior initial point
66
+ ta, tb, intersect = sphere_intersections([0, 0],
67
+ [1, 0], 0.5,
68
+ entire_line=True)
69
+ assert_array_almost_equal([ta, tb], [-0.5, 0.5])
70
+ assert_equal(intersect, True)
71
+
72
+ # No intersection between line and circle
73
+ ta, tb, intersect = sphere_intersections([2, 0],
74
+ [0, 1], 1,
75
+ entire_line=True)
76
+ assert_equal(intersect, False)
77
+
78
+ # Outside initial point pointing toward outside the circle
79
+ ta, tb, intersect = sphere_intersections([2, 0],
80
+ [1, 0], 1,
81
+ entire_line=True)
82
+ assert_array_almost_equal([ta, tb], [-3, -1])
83
+ assert_equal(intersect, True)
84
+
85
+ # Outside initial point pointing toward inside the circle
86
+ ta, tb, intersect = sphere_intersections([2, 0],
87
+ [-1, 0], 1.5,
88
+ entire_line=True)
89
+ assert_array_almost_equal([ta, tb], [0.5, 3.5])
90
+ assert_equal(intersect, True)
91
+
92
+ # Initial point on the boundary
93
+ ta, tb, intersect = sphere_intersections([2, 0],
94
+ [1, 0], 2,
95
+ entire_line=True)
96
+ assert_array_almost_equal([ta, tb], [-4, 0])
97
+ assert_equal(intersect, True)
98
+
99
+
100
+ class TestBoxBoundariesIntersections(TestCase):
101
+
102
+ def test_2d_box_constraints(self):
103
+ # Box constraint in the direction of vector d
104
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
105
+ [1, 1], [3, 3])
106
+ assert_array_almost_equal([ta, tb], [0.5, 1])
107
+ assert_equal(intersect, True)
108
+
109
+ # Negative direction
110
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
111
+ [1, -3], [3, -1])
112
+ assert_equal(intersect, False)
113
+
114
+ # Some constraints are absent (set to +/- inf)
115
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
116
+ [-np.inf, 1],
117
+ [np.inf, np.inf])
118
+ assert_array_almost_equal([ta, tb], [0.5, 1])
119
+ assert_equal(intersect, True)
120
+
121
+ # Intersect on the face of the box
122
+ ta, tb, intersect = box_intersections([1, 0], [0, 1],
123
+ [1, 1], [3, 3])
124
+ assert_array_almost_equal([ta, tb], [1, 1])
125
+ assert_equal(intersect, True)
126
+
127
+ # Interior initial point
128
+ ta, tb, intersect = box_intersections([0, 0], [4, 4],
129
+ [-2, -3], [3, 2])
130
+ assert_array_almost_equal([ta, tb], [0, 0.5])
131
+ assert_equal(intersect, True)
132
+
133
+ # No intersection between line and box constraints
134
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
135
+ [-3, -3], [-1, -1])
136
+ assert_equal(intersect, False)
137
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
138
+ [-3, 3], [-1, 1])
139
+ assert_equal(intersect, False)
140
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
141
+ [-3, -np.inf],
142
+ [-1, np.inf])
143
+ assert_equal(intersect, False)
144
+ ta, tb, intersect = box_intersections([0, 0], [1, 100],
145
+ [1, 1], [3, 3])
146
+ assert_equal(intersect, False)
147
+ ta, tb, intersect = box_intersections([0.99, 0], [0, 2],
148
+ [1, 1], [3, 3])
149
+ assert_equal(intersect, False)
150
+
151
+ # Initial point on the boundary
152
+ ta, tb, intersect = box_intersections([2, 2], [0, 1],
153
+ [-2, -2], [2, 2])
154
+ assert_array_almost_equal([ta, tb], [0, 0])
155
+ assert_equal(intersect, True)
156
+
157
+ def test_2d_box_constraints_entire_line(self):
158
+ # Box constraint in the direction of vector d
159
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
160
+ [1, 1], [3, 3],
161
+ entire_line=True)
162
+ assert_array_almost_equal([ta, tb], [0.5, 1.5])
163
+ assert_equal(intersect, True)
164
+
165
+ # Negative direction
166
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
167
+ [1, -3], [3, -1],
168
+ entire_line=True)
169
+ assert_array_almost_equal([ta, tb], [-1.5, -0.5])
170
+ assert_equal(intersect, True)
171
+
172
+ # Some constraints are absent (set to +/- inf)
173
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
174
+ [-np.inf, 1],
175
+ [np.inf, np.inf],
176
+ entire_line=True)
177
+ assert_array_almost_equal([ta, tb], [0.5, np.inf])
178
+ assert_equal(intersect, True)
179
+
180
+ # Intersect on the face of the box
181
+ ta, tb, intersect = box_intersections([1, 0], [0, 1],
182
+ [1, 1], [3, 3],
183
+ entire_line=True)
184
+ assert_array_almost_equal([ta, tb], [1, 3])
185
+ assert_equal(intersect, True)
186
+
187
+ # Interior initial pointoint
188
+ ta, tb, intersect = box_intersections([0, 0], [4, 4],
189
+ [-2, -3], [3, 2],
190
+ entire_line=True)
191
+ assert_array_almost_equal([ta, tb], [-0.5, 0.5])
192
+ assert_equal(intersect, True)
193
+
194
+ # No intersection between line and box constraints
195
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
196
+ [-3, -3], [-1, -1],
197
+ entire_line=True)
198
+ assert_equal(intersect, False)
199
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
200
+ [-3, 3], [-1, 1],
201
+ entire_line=True)
202
+ assert_equal(intersect, False)
203
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
204
+ [-3, -np.inf],
205
+ [-1, np.inf],
206
+ entire_line=True)
207
+ assert_equal(intersect, False)
208
+ ta, tb, intersect = box_intersections([0, 0], [1, 100],
209
+ [1, 1], [3, 3],
210
+ entire_line=True)
211
+ assert_equal(intersect, False)
212
+ ta, tb, intersect = box_intersections([0.99, 0], [0, 2],
213
+ [1, 1], [3, 3],
214
+ entire_line=True)
215
+ assert_equal(intersect, False)
216
+
217
+ # Initial point on the boundary
218
+ ta, tb, intersect = box_intersections([2, 2], [0, 1],
219
+ [-2, -2], [2, 2],
220
+ entire_line=True)
221
+ assert_array_almost_equal([ta, tb], [-4, 0])
222
+ assert_equal(intersect, True)
223
+
224
+ def test_3d_box_constraints(self):
225
+ # Simple case
226
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1],
227
+ [1, 1, 1], [3, 3, 3])
228
+ assert_array_almost_equal([ta, tb], [1, 1])
229
+ assert_equal(intersect, True)
230
+
231
+ # Negative direction
232
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1],
233
+ [1, 1, 1], [3, 3, 3])
234
+ assert_equal(intersect, False)
235
+
236
+ # Interior point
237
+ ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1],
238
+ [1, 1, 1], [3, 3, 3])
239
+ assert_array_almost_equal([ta, tb], [0, 1])
240
+ assert_equal(intersect, True)
241
+
242
+ def test_3d_box_constraints_entire_line(self):
243
+ # Simple case
244
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1],
245
+ [1, 1, 1], [3, 3, 3],
246
+ entire_line=True)
247
+ assert_array_almost_equal([ta, tb], [1, 3])
248
+ assert_equal(intersect, True)
249
+
250
+ # Negative direction
251
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1],
252
+ [1, 1, 1], [3, 3, 3],
253
+ entire_line=True)
254
+ assert_array_almost_equal([ta, tb], [-3, -1])
255
+ assert_equal(intersect, True)
256
+
257
+ # Interior point
258
+ ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1],
259
+ [1, 1, 1], [3, 3, 3],
260
+ entire_line=True)
261
+ assert_array_almost_equal([ta, tb], [-1, 1])
262
+ assert_equal(intersect, True)
263
+
264
+
265
+ class TestBoxSphereBoundariesIntersections(TestCase):
266
+
267
+ def test_2d_box_constraints(self):
268
+ # Both constraints are active
269
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2],
270
+ [-1, -2], [1, 2], 2,
271
+ entire_line=False)
272
+ assert_array_almost_equal([ta, tb], [0, 0.5])
273
+ assert_equal(intersect, True)
274
+
275
+ # None of the constraints are active
276
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1],
277
+ [-1, -3], [1, 3], 10,
278
+ entire_line=False)
279
+ assert_array_almost_equal([ta, tb], [0, 1])
280
+ assert_equal(intersect, True)
281
+
282
+ # Box constraints are active
283
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
284
+ [-1, -3], [1, 3], 10,
285
+ entire_line=False)
286
+ assert_array_almost_equal([ta, tb], [0, 0.5])
287
+ assert_equal(intersect, True)
288
+
289
+ # Spherical constraints are active
290
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
291
+ [-1, -3], [1, 3], 2,
292
+ entire_line=False)
293
+ assert_array_almost_equal([ta, tb], [0, 0.25])
294
+ assert_equal(intersect, True)
295
+
296
+ # Infeasible problems
297
+ ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4],
298
+ [-1, -3], [1, 3], 2,
299
+ entire_line=False)
300
+ assert_equal(intersect, False)
301
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
302
+ [2, 4], [2, 4], 2,
303
+ entire_line=False)
304
+ assert_equal(intersect, False)
305
+
306
+ def test_2d_box_constraints_entire_line(self):
307
+ # Both constraints are active
308
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2],
309
+ [-1, -2], [1, 2], 2,
310
+ entire_line=True)
311
+ assert_array_almost_equal([ta, tb], [0, 0.5])
312
+ assert_equal(intersect, True)
313
+
314
+ # None of the constraints are active
315
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1],
316
+ [-1, -3], [1, 3], 10,
317
+ entire_line=True)
318
+ assert_array_almost_equal([ta, tb], [0, 2])
319
+ assert_equal(intersect, True)
320
+
321
+ # Box constraints are active
322
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
323
+ [-1, -3], [1, 3], 10,
324
+ entire_line=True)
325
+ assert_array_almost_equal([ta, tb], [0, 0.5])
326
+ assert_equal(intersect, True)
327
+
328
+ # Spherical constraints are active
329
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
330
+ [-1, -3], [1, 3], 2,
331
+ entire_line=True)
332
+ assert_array_almost_equal([ta, tb], [0, 0.25])
333
+ assert_equal(intersect, True)
334
+
335
+ # Infeasible problems
336
+ ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4],
337
+ [-1, -3], [1, 3], 2,
338
+ entire_line=True)
339
+ assert_equal(intersect, False)
340
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
341
+ [2, 4], [2, 4], 2,
342
+ entire_line=True)
343
+ assert_equal(intersect, False)
344
+
345
+
346
+ class TestModifiedDogleg(TestCase):
347
+
348
+ def test_cauchypoint_equalsto_newtonpoint(self):
349
+ A = np.array([[1, 8]])
350
+ b = np.array([-16])
351
+ _, _, Y = projections(A)
352
+ newton_point = np.array([0.24615385, 1.96923077])
353
+
354
+ # Newton point inside boundaries
355
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [np.inf, np.inf])
356
+ assert_array_almost_equal(x, newton_point)
357
+
358
+ # Spherical constraint active
359
+ x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf], [np.inf, np.inf])
360
+ assert_array_almost_equal(x, newton_point/np.linalg.norm(newton_point))
361
+
362
+ # Box constraints active
363
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [0.1, np.inf])
364
+ assert_array_almost_equal(x, (newton_point/newton_point[0]) * 0.1)
365
+
366
+ def test_3d_example(self):
367
+ A = np.array([[1, 8, 1],
368
+ [4, 2, 2]])
369
+ b = np.array([-16, 2])
370
+ Z, LS, Y = projections(A)
371
+
372
+ newton_point = np.array([-1.37090909, 2.23272727, -0.49090909])
373
+ cauchy_point = np.array([0.11165723, 1.73068711, 0.16748585])
374
+ origin = np.zeros_like(newton_point)
375
+
376
+ # newton_point inside boundaries
377
+ x = modified_dogleg(A, Y, b, 3, [-np.inf, -np.inf, -np.inf],
378
+ [np.inf, np.inf, np.inf])
379
+ assert_array_almost_equal(x, newton_point)
380
+
381
+ # line between cauchy_point and newton_point contains best point
382
+ # (spherical constraint is active).
383
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf],
384
+ [np.inf, np.inf, np.inf])
385
+ z = cauchy_point
386
+ d = newton_point-cauchy_point
387
+ t = ((x-z)/(d))
388
+ assert_array_almost_equal(t, np.full(3, 0.40807330))
389
+ assert_array_almost_equal(np.linalg.norm(x), 2)
390
+
391
+ # line between cauchy_point and newton_point contains best point
392
+ # (box constraint is active).
393
+ x = modified_dogleg(A, Y, b, 5, [-1, -np.inf, -np.inf],
394
+ [np.inf, np.inf, np.inf])
395
+ z = cauchy_point
396
+ d = newton_point-cauchy_point
397
+ t = ((x-z)/(d))
398
+ assert_array_almost_equal(t, np.full(3, 0.7498195))
399
+ assert_array_almost_equal(x[0], -1)
400
+
401
+ # line between origin and cauchy_point contains best point
402
+ # (spherical constraint is active).
403
+ x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf, -np.inf],
404
+ [np.inf, np.inf, np.inf])
405
+ z = origin
406
+ d = cauchy_point
407
+ t = ((x-z)/(d))
408
+ assert_array_almost_equal(t, np.full(3, 0.573936265))
409
+ assert_array_almost_equal(np.linalg.norm(x), 1)
410
+
411
+ # line between origin and newton_point contains best point
412
+ # (box constraint is active).
413
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf],
414
+ [np.inf, 1, np.inf])
415
+ z = origin
416
+ d = newton_point
417
+ t = ((x-z)/(d))
418
+ assert_array_almost_equal(t, np.full(3, 0.4478827364))
419
+ assert_array_almost_equal(x[1], 1)
420
+
421
+
422
+ class TestProjectCG(TestCase):
423
+
424
+ # From Example 16.2 Nocedal/Wright "Numerical
425
+ # Optimization" p.452.
426
+ def test_nocedal_example(self):
427
+ H = csc_matrix([[6, 2, 1],
428
+ [2, 5, 2],
429
+ [1, 2, 4]])
430
+ A = csc_matrix([[1, 0, 1],
431
+ [0, 1, 1]])
432
+ c = np.array([-8, -3, -3])
433
+ b = -np.array([3, 0])
434
+ Z, _, Y = projections(A)
435
+ x, info = projected_cg(H, c, Z, Y, b)
436
+ assert_equal(info["stop_cond"], 4)
437
+ assert_equal(info["hits_boundary"], False)
438
+ assert_array_almost_equal(x, [2, -1, 1])
439
+
440
+ def test_compare_with_direct_fact(self):
441
+ H = csc_matrix([[6, 2, 1, 3],
442
+ [2, 5, 2, 4],
443
+ [1, 2, 4, 5],
444
+ [3, 4, 5, 7]])
445
+ A = csc_matrix([[1, 0, 1, 0],
446
+ [0, 1, 1, 1]])
447
+ c = np.array([-2, -3, -3, 1])
448
+ b = -np.array([3, 0])
449
+ Z, _, Y = projections(A)
450
+ x, info = projected_cg(H, c, Z, Y, b, tol=0)
451
+ x_kkt, _ = eqp_kktfact(H, c, A, b)
452
+ assert_equal(info["stop_cond"], 1)
453
+ assert_equal(info["hits_boundary"], False)
454
+ assert_array_almost_equal(x, x_kkt)
455
+
456
+ def test_trust_region_infeasible(self):
457
+ H = csc_matrix([[6, 2, 1, 3],
458
+ [2, 5, 2, 4],
459
+ [1, 2, 4, 5],
460
+ [3, 4, 5, 7]])
461
+ A = csc_matrix([[1, 0, 1, 0],
462
+ [0, 1, 1, 1]])
463
+ c = np.array([-2, -3, -3, 1])
464
+ b = -np.array([3, 0])
465
+ trust_radius = 1
466
+ Z, _, Y = projections(A)
467
+ with pytest.raises(ValueError):
468
+ projected_cg(H, c, Z, Y, b, trust_radius=trust_radius)
469
+
470
+ def test_trust_region_barely_feasible(self):
471
+ H = csc_matrix([[6, 2, 1, 3],
472
+ [2, 5, 2, 4],
473
+ [1, 2, 4, 5],
474
+ [3, 4, 5, 7]])
475
+ A = csc_matrix([[1, 0, 1, 0],
476
+ [0, 1, 1, 1]])
477
+ c = np.array([-2, -3, -3, 1])
478
+ b = -np.array([3, 0])
479
+ trust_radius = 2.32379000772445021283
480
+ Z, _, Y = projections(A)
481
+ x, info = projected_cg(H, c, Z, Y, b,
482
+ tol=0,
483
+ trust_radius=trust_radius)
484
+ assert_equal(info["stop_cond"], 2)
485
+ assert_equal(info["hits_boundary"], True)
486
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
487
+ assert_array_almost_equal(x, -Y.dot(b))
488
+
489
+ def test_hits_boundary(self):
490
+ H = csc_matrix([[6, 2, 1, 3],
491
+ [2, 5, 2, 4],
492
+ [1, 2, 4, 5],
493
+ [3, 4, 5, 7]])
494
+ A = csc_matrix([[1, 0, 1, 0],
495
+ [0, 1, 1, 1]])
496
+ c = np.array([-2, -3, -3, 1])
497
+ b = -np.array([3, 0])
498
+ trust_radius = 3
499
+ Z, _, Y = projections(A)
500
+ x, info = projected_cg(H, c, Z, Y, b,
501
+ tol=0,
502
+ trust_radius=trust_radius)
503
+ assert_equal(info["stop_cond"], 2)
504
+ assert_equal(info["hits_boundary"], True)
505
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
506
+
507
+ def test_negative_curvature_unconstrained(self):
508
+ H = csc_matrix([[1, 2, 1, 3],
509
+ [2, 0, 2, 4],
510
+ [1, 2, 0, 2],
511
+ [3, 4, 2, 0]])
512
+ A = csc_matrix([[1, 0, 1, 0],
513
+ [0, 1, 0, 1]])
514
+ c = np.array([-2, -3, -3, 1])
515
+ b = -np.array([3, 0])
516
+ Z, _, Y = projections(A)
517
+ with pytest.raises(ValueError):
518
+ projected_cg(H, c, Z, Y, b, tol=0)
519
+
520
+ def test_negative_curvature(self):
521
+ H = csc_matrix([[1, 2, 1, 3],
522
+ [2, 0, 2, 4],
523
+ [1, 2, 0, 2],
524
+ [3, 4, 2, 0]])
525
+ A = csc_matrix([[1, 0, 1, 0],
526
+ [0, 1, 0, 1]])
527
+ c = np.array([-2, -3, -3, 1])
528
+ b = -np.array([3, 0])
529
+ Z, _, Y = projections(A)
530
+ trust_radius = 1000
531
+ x, info = projected_cg(H, c, Z, Y, b,
532
+ tol=0,
533
+ trust_radius=trust_radius)
534
+ assert_equal(info["stop_cond"], 3)
535
+ assert_equal(info["hits_boundary"], True)
536
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
537
+
538
+ # The box constraints are inactive at the solution but
539
+ # are active during the iterations.
540
+ def test_inactive_box_constraints(self):
541
+ H = csc_matrix([[6, 2, 1, 3],
542
+ [2, 5, 2, 4],
543
+ [1, 2, 4, 5],
544
+ [3, 4, 5, 7]])
545
+ A = csc_matrix([[1, 0, 1, 0],
546
+ [0, 1, 1, 1]])
547
+ c = np.array([-2, -3, -3, 1])
548
+ b = -np.array([3, 0])
549
+ Z, _, Y = projections(A)
550
+ x, info = projected_cg(H, c, Z, Y, b,
551
+ tol=0,
552
+ lb=[0.5, -np.inf,
553
+ -np.inf, -np.inf],
554
+ return_all=True)
555
+ x_kkt, _ = eqp_kktfact(H, c, A, b)
556
+ assert_equal(info["stop_cond"], 1)
557
+ assert_equal(info["hits_boundary"], False)
558
+ assert_array_almost_equal(x, x_kkt)
559
+
560
+ # The box constraints active and the termination is
561
+ # by maximum iterations (infeasible interaction).
562
+ def test_active_box_constraints_maximum_iterations_reached(self):
563
+ H = csc_matrix([[6, 2, 1, 3],
564
+ [2, 5, 2, 4],
565
+ [1, 2, 4, 5],
566
+ [3, 4, 5, 7]])
567
+ A = csc_matrix([[1, 0, 1, 0],
568
+ [0, 1, 1, 1]])
569
+ c = np.array([-2, -3, -3, 1])
570
+ b = -np.array([3, 0])
571
+ Z, _, Y = projections(A)
572
+ x, info = projected_cg(H, c, Z, Y, b,
573
+ tol=0,
574
+ lb=[0.8, -np.inf,
575
+ -np.inf, -np.inf],
576
+ return_all=True)
577
+ assert_equal(info["stop_cond"], 1)
578
+ assert_equal(info["hits_boundary"], True)
579
+ assert_array_almost_equal(A.dot(x), -b)
580
+ assert_array_almost_equal(x[0], 0.8)
581
+
582
+ # The box constraints are active and the termination is
583
+ # because it hits boundary (without infeasible interaction).
584
+ def test_active_box_constraints_hits_boundaries(self):
585
+ H = csc_matrix([[6, 2, 1, 3],
586
+ [2, 5, 2, 4],
587
+ [1, 2, 4, 5],
588
+ [3, 4, 5, 7]])
589
+ A = csc_matrix([[1, 0, 1, 0],
590
+ [0, 1, 1, 1]])
591
+ c = np.array([-2, -3, -3, 1])
592
+ b = -np.array([3, 0])
593
+ trust_radius = 3
594
+ Z, _, Y = projections(A)
595
+ x, info = projected_cg(H, c, Z, Y, b,
596
+ tol=0,
597
+ ub=[np.inf, np.inf, 1.6, np.inf],
598
+ trust_radius=trust_radius,
599
+ return_all=True)
600
+ assert_equal(info["stop_cond"], 2)
601
+ assert_equal(info["hits_boundary"], True)
602
+ assert_array_almost_equal(x[2], 1.6)
603
+
604
+ # The box constraints are active and the termination is
605
+ # because it hits boundary (infeasible interaction).
606
+ def test_active_box_constraints_hits_boundaries_infeasible_iter(self):
607
+ H = csc_matrix([[6, 2, 1, 3],
608
+ [2, 5, 2, 4],
609
+ [1, 2, 4, 5],
610
+ [3, 4, 5, 7]])
611
+ A = csc_matrix([[1, 0, 1, 0],
612
+ [0, 1, 1, 1]])
613
+ c = np.array([-2, -3, -3, 1])
614
+ b = -np.array([3, 0])
615
+ trust_radius = 4
616
+ Z, _, Y = projections(A)
617
+ x, info = projected_cg(H, c, Z, Y, b,
618
+ tol=0,
619
+ ub=[np.inf, 0.1, np.inf, np.inf],
620
+ trust_radius=trust_radius,
621
+ return_all=True)
622
+ assert_equal(info["stop_cond"], 2)
623
+ assert_equal(info["hits_boundary"], True)
624
+ assert_array_almost_equal(x[1], 0.1)
625
+
626
+ # The box constraints are active and the termination is
627
+ # because it hits boundary (no infeasible interaction).
628
+ def test_active_box_constraints_negative_curvature(self):
629
+ H = csc_matrix([[1, 2, 1, 3],
630
+ [2, 0, 2, 4],
631
+ [1, 2, 0, 2],
632
+ [3, 4, 2, 0]])
633
+ A = csc_matrix([[1, 0, 1, 0],
634
+ [0, 1, 0, 1]])
635
+ c = np.array([-2, -3, -3, 1])
636
+ b = -np.array([3, 0])
637
+ Z, _, Y = projections(A)
638
+ trust_radius = 1000
639
+ x, info = projected_cg(H, c, Z, Y, b,
640
+ tol=0,
641
+ ub=[np.inf, np.inf, 100, np.inf],
642
+ trust_radius=trust_radius)
643
+ assert_equal(info["stop_cond"], 3)
644
+ assert_equal(info["hits_boundary"], True)
645
+ assert_array_almost_equal(x[2], 100)
parrot/lib/python3.10/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import numpy as np
3
+ from scipy.optimize import minimize, Bounds
4
+
5
+ def test_gh10880():
6
+ # checks that verbose reporting works with trust-constr for
7
+ # bound-contrained problems
8
+ bnds = Bounds(1, 2)
9
+ opts = {'maxiter': 1000, 'verbose': 2}
10
+ minimize(lambda x: x**2, x0=2., method='trust-constr',
11
+ bounds=bnds, options=opts)
12
+
13
+ opts = {'maxiter': 1000, 'verbose': 3}
14
+ minimize(lambda x: x**2, x0=2., method='trust-constr',
15
+ bounds=bnds, options=opts)
16
+
17
+ @pytest.mark.xslow
18
+ def test_gh12922():
19
+ # checks that verbose reporting works with trust-constr for
20
+ # general constraints
21
+ def objective(x):
22
+ return np.array([(np.sum((x+1)**4))])
23
+
24
+ cons = {'type': 'ineq', 'fun': lambda x: -x[0]**2}
25
+ n = 25
26
+ x0 = np.linspace(-5, 5, n)
27
+
28
+ opts = {'maxiter': 1000, 'verbose': 2}
29
+ minimize(objective, x0=x0, method='trust-constr',
30
+ constraints=cons, options=opts)
31
+
32
+ opts = {'maxiter': 1000, 'verbose': 3}
33
+ minimize(objective, x0=x0, method='trust-constr',
34
+ constraints=cons, options=opts)
vllm/lib/python3.10/site-packages/transformers/generation/__pycache__/logits_process.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83b349ed862ec45f0013a5aed6f0b165e3f93f9b6ac9d35f1ca94c149e36cc55
3
+ size 121302
vllm/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9063b9d40ec0d4ed1c0bbefe449b7c458fb783f45c308f4e60f9b2eb15a5c241
3
+ size 103620
vllm/lib/python3.10/site-packages/transformers/models/bloom/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_bloom import *
22
+ from .modeling_bloom import *
23
+ from .modeling_flax_bloom import *
24
+ from .tokenization_bloom_fast import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (599 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-310.pyc ADDED
Binary file (8.7 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/bloom/configuration_bloom.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 the Big Science Workshop and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Bloom configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import TYPE_CHECKING, Any, List, Mapping, Optional
19
+
20
+ from packaging import version
21
+
22
+
23
+ if TYPE_CHECKING:
24
+ from ... import PreTrainedTokenizer, TensorType
25
+
26
+ from ...configuration_utils import PretrainedConfig
27
+ from ...onnx import OnnxConfigWithPast, PatchingSpec
28
+ from ...utils import is_torch_available, logging
29
+
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+
34
+ class BloomConfig(PretrainedConfig):
35
+ """
36
+ This is the configuration class to store the configuration of a [`BloomModel`]. It is used to instantiate a Bloom
37
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
38
+ defaults will yield a similar configuration to the Bloom architecture
39
+ [bigscience/bloom](https://huggingface.co/bigscience/bloom).
40
+
41
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
42
+ documentation from [`PretrainedConfig`] for more information.
43
+
44
+
45
+ Args:
46
+ vocab_size (`int`, *optional*, defaults to 250880):
47
+ Vocabulary size of the Bloom model. Defines the maximum number of different tokens that can be represented
48
+ by the `inputs_ids` passed when calling [`BloomModel`]. Check [this
49
+ discussion](https://huggingface.co/bigscience/bloom/discussions/120#633d28389addb8530b406c2a) on how the
50
+ `vocab_size` has been defined.
51
+ hidden_size (`int`, *optional*, defaults to 64):
52
+ Dimensionality of the embeddings and hidden states.
53
+ n_layer (`int`, *optional*, defaults to 2):
54
+ Number of hidden layers in the Transformer encoder.
55
+ n_head (`int`, *optional*, defaults to 8):
56
+ Number of attention heads for each attention layer in the Transformer encoder.
57
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
58
+ The epsilon to use in the layer normalization layers.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ apply_residual_connection_post_layernorm (`bool`, *optional*, defaults to `False`):
62
+ If enabled, use the layer norm of the hidden states as the residual in the transformer blocks
63
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
64
+ Dropout rate of the dropout function on the bias dropout.
65
+ attention_dropout (`float`, *optional*, defaults to 0.1):
66
+ Dropout rate applied to the attention probs
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models).
69
+ pretraining_tp (`int`, *optional*, defaults to `1`):
70
+ Experimental feature. Tensor parallelism rank used during pretraining with Megatron. Please refer to [this
71
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
72
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
73
+ issue](https://github.com/pytorch/pytorch/issues/76232). Note also that this is enabled only when
74
+ `slow_but_exact=True`.
75
+ slow_but_exact (`bool`, *optional*, defaults to `False`):
76
+ Experimental feature. Whether to use slow but exact implementation of the attention mechanism. While
77
+ merging the TP rank tensors, due to slicing operations the results may be slightly different between the
78
+ model trained on Megatron and our model. Please refer to [this
79
+ issue](https://github.com/pytorch/pytorch/issues/76232). A solution to obtain more accurate results is to
80
+ enable this feature. Enabling this will hurt the computational time of the inference. Will be probably
81
+ resolved in the future once the main model has been fine-tuned with TP_rank=1.
82
+
83
+ Example:
84
+
85
+ ```python
86
+ >>> from transformers import BloomConfig, BloomModel
87
+
88
+ >>> # Initializing a Bloom configuration
89
+ >>> configuration = BloomConfig()
90
+
91
+ >>> # Initializing a model (with random weights) from the configuration
92
+ >>> model = BloomModel(configuration)
93
+
94
+ >>> # Accessing the model configuration
95
+ >>> configuration = model.config
96
+ ```"""
97
+
98
+ model_type = "bloom"
99
+ keys_to_ignore_at_inference = ["past_key_values"]
100
+ attribute_map = {
101
+ "num_hidden_layers": "n_layer",
102
+ "num_attention_heads": "n_head",
103
+ }
104
+
105
+ def __init__(
106
+ self,
107
+ vocab_size=250880,
108
+ hidden_size=64,
109
+ n_layer=2,
110
+ n_head=8,
111
+ layer_norm_epsilon=1e-5,
112
+ initializer_range=0.02,
113
+ use_cache=True,
114
+ bos_token_id=1,
115
+ eos_token_id=2,
116
+ apply_residual_connection_post_layernorm=False,
117
+ hidden_dropout=0.0,
118
+ attention_dropout=0.0,
119
+ pretraining_tp=1, # TP rank used when training with megatron
120
+ slow_but_exact=False,
121
+ **kwargs,
122
+ ):
123
+ self.vocab_size = vocab_size
124
+ # Backward compatibility with n_embed kwarg
125
+ n_embed = kwargs.pop("n_embed", None)
126
+ self.hidden_size = hidden_size if n_embed is None else n_embed
127
+ self.n_layer = n_layer
128
+ self.n_head = n_head
129
+ self.layer_norm_epsilon = layer_norm_epsilon
130
+ self.initializer_range = initializer_range
131
+ self.use_cache = use_cache
132
+ self.pretraining_tp = pretraining_tp
133
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
134
+ self.hidden_dropout = hidden_dropout
135
+ self.attention_dropout = attention_dropout
136
+
137
+ self.bos_token_id = bos_token_id
138
+ self.eos_token_id = eos_token_id
139
+ self.slow_but_exact = slow_but_exact
140
+
141
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
142
+
143
+
144
+ class BloomOnnxConfig(OnnxConfigWithPast):
145
+ torch_onnx_minimum_version = version.parse("1.12")
146
+
147
+ def __init__(
148
+ self,
149
+ config: PretrainedConfig,
150
+ task: str = "default",
151
+ patching_specs: List[PatchingSpec] = None,
152
+ use_past: bool = False,
153
+ ):
154
+ super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
155
+ if not getattr(self._config, "pad_token_id", None):
156
+ # TODO: how to do that better?
157
+ self._config.pad_token_id = 0
158
+
159
+ @property
160
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
161
+ common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
162
+ if self.use_past:
163
+ # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
164
+ self.fill_with_past_key_values_(common_inputs, direction="inputs", inverted_values_shape=True)
165
+ common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
166
+ else:
167
+ common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
168
+
169
+ return common_inputs
170
+
171
+ @property
172
+ def num_layers(self) -> int:
173
+ return self._config.n_layer
174
+
175
+ @property
176
+ def num_attention_heads(self) -> int:
177
+ return self._config.n_head
178
+
179
+ @property
180
+ def atol_for_validation(self) -> float:
181
+ return 1e-3
182
+
183
+ def generate_dummy_inputs(
184
+ self,
185
+ tokenizer: "PreTrainedTokenizer",
186
+ batch_size: int = -1,
187
+ seq_length: int = -1,
188
+ is_pair: bool = False,
189
+ framework: Optional["TensorType"] = None,
190
+ ) -> Mapping[str, Any]:
191
+ common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
192
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
193
+ )
194
+
195
+ # We need to order the input in the way they appears in the forward()
196
+ ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
197
+
198
+ # Need to add the past_keys
199
+ if self.use_past:
200
+ if not is_torch_available():
201
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
202
+ else:
203
+ import torch
204
+
205
+ batch, seqlen = common_inputs["input_ids"].shape
206
+ # Not using the same length for past_key_values
207
+ past_key_values_length = seqlen + 2
208
+ head_dim = self._config.hidden_size // self.num_attention_heads
209
+ past_key_shape = (
210
+ batch * self.num_attention_heads,
211
+ head_dim,
212
+ past_key_values_length,
213
+ )
214
+ past_value_shape = (
215
+ batch * self.num_attention_heads,
216
+ past_key_values_length,
217
+ head_dim,
218
+ )
219
+ ordered_inputs["past_key_values"] = [
220
+ (torch.zeros(past_key_shape), torch.zeros(past_value_shape)) for _ in range(self.num_layers)
221
+ ]
222
+
223
+ ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
224
+ if self.use_past:
225
+ mask_dtype = ordered_inputs["attention_mask"].dtype
226
+ ordered_inputs["attention_mask"] = torch.cat(
227
+ [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
228
+ )
229
+
230
+ return ordered_inputs
231
+
232
+ @property
233
+ def default_onnx_opset(self) -> int:
234
+ return 13
235
+
236
+
237
+ __all__ = ["BloomConfig", "BloomOnnxConfig"]
vllm/lib/python3.10/site-packages/transformers/models/bloom/modeling_bloom.py ADDED
@@ -0,0 +1,1398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 HuggingFace Inc. team and BigScience workshop.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch BLOOM model."""
16
+
17
+ import math
18
+ import warnings
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
25
+ from torch.nn import functional as F
26
+
27
+ from ...cache_utils import Cache, DynamicCache, StaticCache
28
+ from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
29
+ from ...generation import GenerationMixin
30
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
31
+ from ...modeling_outputs import (
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ CausalLMOutputWithCrossAttentions,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from ...modeling_utils import PreTrainedModel
39
+ from ...utils import (
40
+ is_torch_flex_attn_available,
41
+ logging,
42
+ )
43
+ from .configuration_bloom import BloomConfig
44
+
45
+
46
+ if is_torch_flex_attn_available():
47
+ from torch.nn.attention.flex_attention import BlockMask
48
+
49
+ from ...integrations.flex_attention import make_flex_block_causal_mask
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ _CHECKPOINT_FOR_DOC = "bigscience/bloom-560m"
55
+ _CONFIG_FOR_DOC = "BloomConfig"
56
+
57
+
58
+ def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
59
+ """
60
+ Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it
61
+ relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
62
+ `softmax(l+a) = softmax(l)`. Based on
63
+ https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
64
+ TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly.
65
+
66
+ Args:
67
+ Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
68
+ attention_mask (`torch.Tensor`):
69
+ Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
70
+ num_heads (`int`):
71
+ number of heads
72
+ dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`):
73
+ dtype of the output tensor
74
+ """
75
+ batch_size, seq_length = attention_mask.shape
76
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
77
+ base = torch.tensor(
78
+ 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
79
+ )
80
+ powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
81
+ slopes = torch.pow(base, powers)
82
+
83
+ if closest_power_of_2 != num_heads:
84
+ extra_base = torch.tensor(
85
+ 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
86
+ )
87
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
88
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
89
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
90
+
91
+ # Note: alibi will added to the attention bias that will be applied to the query, key product of attention
92
+ # => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
93
+ # => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
94
+ # => the query_length dimension will then be broadcasted correctly
95
+ # This is more or less identical to T5's relative position bias:
96
+ # https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
97
+ arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
98
+ alibi = slopes[..., None] * arange_tensor
99
+ return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
100
+
101
+
102
+ def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
103
+ """
104
+ Dropout add function
105
+
106
+ Args:
107
+ x (`torch.tensor`):
108
+ input tensor
109
+ residual (`torch.tensor`):
110
+ residual tensor
111
+ prob (`float`):
112
+ dropout probability
113
+ training (`bool`):
114
+ training mode
115
+ """
116
+ out = F.dropout(x, p=prob, training=training)
117
+ out = residual + out
118
+ return out
119
+
120
+
121
+ def bloom_gelu_forward(x: torch.Tensor) -> torch.Tensor:
122
+ """
123
+ Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
124
+ make the model jitable.
125
+
126
+ Args:
127
+ x (`torch.tensor`):
128
+ input hidden states
129
+ """
130
+ return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))
131
+
132
+
133
+ def bloom_gelu_back(g: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
134
+ """
135
+ gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) +
136
+ 0.3989423 * x * torch.exp(-0.5 * x * x)
137
+
138
+ Args:
139
+ g (`torch.tensor`):
140
+ gradient output tensor
141
+ x (`torch.tensor`):
142
+ input tensor
143
+ """
144
+ x = x[0] # x is a tuple of 1 element, needs to unpack it first
145
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
146
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
147
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh_out)
148
+ return ff * g
149
+
150
+
151
+ class GeLUFunction(torch.autograd.Function):
152
+ @staticmethod
153
+ def forward(ctx, input: torch.Tensor) -> torch.Tensor:
154
+ ctx.save_for_backward(input)
155
+ return bloom_gelu_forward(input)
156
+
157
+ @staticmethod
158
+ def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
159
+ input = ctx.saved_tensors
160
+ tmp = bloom_gelu_back(grad_output, input)
161
+ return tmp
162
+
163
+
164
+ class BloomGelu(nn.Module):
165
+ """
166
+ BloomBiasGelu wrapper function that make use of the simple function on inference mode to make the model
167
+ torchscriptable and use the autograd function in training mode to get the accurate results of the gradients Partly
168
+ copied from Megatron-DeepSpeed code and adapted for our needs
169
+
170
+ See here why autograd functions are not torchscriptable: https://github.com/pytorch/pytorch/issues/22329
171
+ """
172
+
173
+ def __init__(self):
174
+ super().__init__()
175
+
176
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
177
+ if self.training:
178
+ return GeLUFunction.apply(x)
179
+ else:
180
+ return bloom_gelu_forward(x)
181
+
182
+
183
+ class BloomAttention(nn.Module):
184
+ def __init__(self, config: BloomConfig, layer_idx: Optional[int] = None):
185
+ super().__init__()
186
+
187
+ self.pretraining_tp = config.pretraining_tp
188
+ self.slow_but_exact = config.slow_but_exact
189
+
190
+ self.hidden_size = config.hidden_size
191
+ self.num_heads = config.n_head
192
+ self.head_dim = self.hidden_size // self.num_heads
193
+ self.split_size = self.hidden_size
194
+ self.hidden_dropout = config.hidden_dropout
195
+
196
+ if self.head_dim * self.num_heads != self.hidden_size:
197
+ raise ValueError(
198
+ f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
199
+ f" {self.num_heads})."
200
+ )
201
+
202
+ # Layer-wise attention scaling
203
+ self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
204
+ self.beta = 1.0
205
+ self.layer_idx = layer_idx
206
+ if layer_idx is None:
207
+ logger.warning_once(
208
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
209
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
210
+ "when creating this class."
211
+ )
212
+
213
+ self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=True)
214
+ self.dense = nn.Linear(self.hidden_size, self.hidden_size)
215
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
216
+
217
+ def _reshape(self, fused_qkv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
218
+ """
219
+ Split the last dimension into (num_heads, head_dim) and reshapes to (bs, heads, len, dim) shape
220
+ without making any copies, results share same memory storage as `fused_qkv`
221
+
222
+ Args:
223
+ fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim]
224
+
225
+ Returns:
226
+ query: [batch_size, num_heads, seq_length, head_dim]
227
+ key: [batch_size, num_heads, seq_length, head_dim]
228
+ value: [batch_size, num_heads, seq_length, head_dim]
229
+ """
230
+ batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
231
+ fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
232
+ query_layer = fused_qkv[..., 0, :].transpose(1, 2)
233
+ key_layer = fused_qkv[..., 1, :].transpose(1, 2)
234
+ value_layer = fused_qkv[..., 2, :].transpose(1, 2)
235
+ return query_layer, key_layer, value_layer
236
+
237
+ def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
238
+ """
239
+ Merge heads together over the last dimension
240
+
241
+ Args:
242
+ x (`torch.tensor`): [batch_size * num_heads, seq_length, head_dim]
243
+
244
+ Returns:
245
+ torch.tensor: [batch_size, seq_length, num_heads * head_dim]
246
+ """
247
+ # What we want to achieve is:
248
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
249
+ batch_size_and_num_heads, seq_length, _ = x.shape
250
+ batch_size = batch_size_and_num_heads // self.num_heads
251
+
252
+ # First view to decompose the batch size
253
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
254
+ x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
255
+
256
+ # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
257
+ x = x.permute(0, 2, 1, 3)
258
+
259
+ # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
260
+ return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
261
+
262
+ def forward(
263
+ self,
264
+ hidden_states: torch.Tensor,
265
+ residual: torch.Tensor,
266
+ alibi: torch.Tensor,
267
+ attention_mask: torch.Tensor,
268
+ layer_past: Optional[Cache] = None,
269
+ head_mask: Optional[torch.Tensor] = None,
270
+ use_cache: bool = False,
271
+ output_attentions: bool = False,
272
+ cache_position: Optional[torch.LongTensor] = None,
273
+ ):
274
+ batch_size, q_length, _ = hidden_states.shape
275
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
276
+ # 3 x [batch_size, num_heads, seq_length, head_dim]
277
+ query_layer, key_layer, value_layer = self._reshape(fused_qkv)
278
+
279
+ if layer_past is not None:
280
+ cache_kwargs = {"cache_position": cache_position}
281
+ key_layer, value_layer = layer_past.update(key_layer, value_layer, self.layer_idx, cache_kwargs)
282
+
283
+ # reshape qkv for further computations
284
+ query_layer = query_layer.reshape(batch_size * self.num_heads, -1, self.head_dim)
285
+ key_layer = key_layer.reshape(batch_size * self.num_heads, -1, self.head_dim).transpose(-1, -2)
286
+ value_layer = value_layer.reshape(batch_size * self.num_heads, -1, self.head_dim)
287
+
288
+ # [batch_size * num_heads, q_length, kv_length]
289
+ attention_scores = alibi.baddbmm(
290
+ batch1=query_layer,
291
+ batch2=key_layer,
292
+ beta=self.beta,
293
+ alpha=self.inv_norm_factor,
294
+ )
295
+
296
+ # change view to [batch_size, num_heads, q_length, kv_length]
297
+ attn_weights = attention_scores.view(batch_size, self.num_heads, q_length, -1)
298
+ if attention_mask is not None: # no matter the length, we just slice it
299
+ causal_mask = attention_mask[:, :, :, : key_layer.shape[-1]]
300
+ attn_weights = attn_weights + causal_mask
301
+
302
+ # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype
303
+ attention_probs = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_layer.dtype)
304
+
305
+ # [batch_size, num_heads, q_length, kv_length]
306
+ attention_probs = self.attention_dropout(attention_probs)
307
+
308
+ if head_mask is not None:
309
+ attention_probs = attention_probs * head_mask
310
+
311
+ # change view [batch_size x num_heads, q_length, kv_length]
312
+ attention_probs_reshaped = attention_probs.view(batch_size * self.num_heads, q_length, -1)
313
+
314
+ # matmul: [batch_size * num_heads, q_length, head_dim]
315
+ context_layer = torch.bmm(attention_probs_reshaped, value_layer)
316
+
317
+ # change view [batch_size, q_length, num_heads * head_dim]
318
+ context_layer = self._merge_heads(context_layer)
319
+
320
+ # aggregate results across tp ranks. See here: https://github.com/pytorch/pytorch/issues/76232
321
+ if self.pretraining_tp > 1 and self.slow_but_exact:
322
+ slices = self.hidden_size / self.pretraining_tp
323
+ output_tensor = torch.zeros_like(context_layer)
324
+ for i in range(self.pretraining_tp):
325
+ output_tensor = output_tensor + F.linear(
326
+ context_layer[:, :, int(i * slices) : int((i + 1) * slices)],
327
+ self.dense.weight[:, int(i * slices) : int((i + 1) * slices)],
328
+ )
329
+ else:
330
+ output_tensor = self.dense(context_layer)
331
+
332
+ output_tensor = dropout_add(output_tensor, residual, self.hidden_dropout, self.training)
333
+
334
+ outputs = (output_tensor, layer_past)
335
+ if output_attentions:
336
+ outputs += (attention_probs,)
337
+
338
+ return outputs
339
+
340
+
341
+ class BloomMLP(nn.Module):
342
+ def __init__(self, config: BloomConfig):
343
+ super().__init__()
344
+ hidden_size = config.hidden_size
345
+
346
+ self.pretraining_tp = config.pretraining_tp
347
+ self.slow_but_exact = config.slow_but_exact
348
+ self.dense_h_to_4h = nn.Linear(hidden_size, 4 * hidden_size)
349
+ self.gelu_impl = BloomGelu()
350
+ self.dense_4h_to_h = nn.Linear(4 * hidden_size, hidden_size)
351
+ self.hidden_dropout = config.hidden_dropout
352
+
353
+ def forward(self, hidden_states: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
354
+ hidden_states = self.gelu_impl(self.dense_h_to_4h(hidden_states))
355
+
356
+ if self.pretraining_tp > 1 and self.slow_but_exact:
357
+ intermediate_output = torch.zeros_like(residual)
358
+ slices = self.dense_4h_to_h.weight.shape[-1] / self.pretraining_tp
359
+ for i in range(self.pretraining_tp):
360
+ intermediate_output = intermediate_output + F.linear(
361
+ hidden_states[:, :, int(i * slices) : int((i + 1) * slices)],
362
+ self.dense_4h_to_h.weight[:, int(i * slices) : int((i + 1) * slices)],
363
+ )
364
+ else:
365
+ intermediate_output = self.dense_4h_to_h(hidden_states)
366
+
367
+ output = dropout_add(intermediate_output, residual, self.hidden_dropout, self.training)
368
+
369
+ return output
370
+
371
+
372
+ class BloomBlock(nn.Module):
373
+ def __init__(self, config: BloomConfig, layer_idx: Optional[int] = None):
374
+ super().__init__()
375
+ hidden_size = config.hidden_size
376
+
377
+ self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
378
+ self.num_heads = config.n_head
379
+ self.self_attention = BloomAttention(config, layer_idx)
380
+ self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
381
+
382
+ self.mlp = BloomMLP(config)
383
+
384
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
385
+ self.hidden_dropout = config.hidden_dropout
386
+
387
+ def forward(
388
+ self,
389
+ hidden_states: torch.Tensor,
390
+ alibi: torch.Tensor,
391
+ attention_mask: torch.Tensor,
392
+ layer_past: Optional[Cache] = None,
393
+ head_mask: Optional[torch.Tensor] = None,
394
+ use_cache: bool = False,
395
+ output_attentions: bool = False,
396
+ cache_position: Optional[torch.LongTensor] = None,
397
+ ):
398
+ # hidden_states: [batch_size, seq_length, hidden_size]
399
+
400
+ # Layer norm at the beginning of the transformer layer.
401
+ layernorm_output = self.input_layernorm(hidden_states)
402
+
403
+ # Layer norm post the self attention.
404
+ if self.apply_residual_connection_post_layernorm:
405
+ residual = layernorm_output
406
+ else:
407
+ residual = hidden_states
408
+
409
+ # Self attention.
410
+ attn_outputs = self.self_attention(
411
+ layernorm_output,
412
+ residual,
413
+ layer_past=layer_past,
414
+ attention_mask=attention_mask,
415
+ alibi=alibi,
416
+ head_mask=head_mask,
417
+ use_cache=use_cache,
418
+ output_attentions=output_attentions,
419
+ cache_position=cache_position,
420
+ )
421
+
422
+ attention_output = attn_outputs[0]
423
+
424
+ outputs = attn_outputs[1:]
425
+
426
+ layernorm_output = self.post_attention_layernorm(attention_output)
427
+
428
+ # Get residual
429
+ if self.apply_residual_connection_post_layernorm:
430
+ residual = layernorm_output
431
+ else:
432
+ residual = attention_output
433
+
434
+ # MLP.
435
+ output = self.mlp(layernorm_output, residual)
436
+
437
+ if use_cache:
438
+ outputs = (output,) + outputs
439
+ else:
440
+ outputs = (output,) + outputs[1:]
441
+
442
+ return outputs # hidden_states, past_kv, attentions
443
+
444
+
445
+ class BloomPreTrainedModel(PreTrainedModel):
446
+ config_class = BloomConfig
447
+ base_model_prefix = "transformer"
448
+ supports_gradient_checkpointing = True
449
+ _no_split_modules = ["BloomBlock"]
450
+ _skip_keys_device_placement = "past_key_values"
451
+ _supports_cache_class = True
452
+ _supports_static_cache = True
453
+ _supports_quantized_cache = True
454
+
455
+ def __init__(self, *inputs, **kwargs):
456
+ super().__init__(*inputs, **kwargs)
457
+
458
+ def _init_weights(self, module: nn.Module):
459
+ """Initialize the weights."""
460
+ if isinstance(module, nn.Linear):
461
+ # Slightly different from the TF version which uses truncated_normal for initialization
462
+ # cf https://github.com/pytorch/pytorch/pull/5617
463
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
464
+ if module.bias is not None:
465
+ module.bias.data.zero_()
466
+ elif isinstance(module, nn.Embedding):
467
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
468
+ if module.padding_idx is not None:
469
+ module.weight.data[module.padding_idx].zero_()
470
+ elif isinstance(module, LayerNorm):
471
+ module.bias.data.zero_()
472
+ module.weight.data.fill_(1.0)
473
+
474
+
475
+ BLOOM_START_DOCSTRING = r"""
476
+
477
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
478
+ library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)
479
+
480
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
481
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
482
+ and behavior.
483
+
484
+ Parameters:
485
+ config ([`BloomConfig`]): Model configuration class with all the parameters of the model.
486
+ Initializing with a config file does not load the weights associated with the model, only the
487
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
488
+ """
489
+
490
+ BLOOM_INPUTS_DOCSTRING = r"""
491
+ Args:
492
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
493
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[2]`
494
+ (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
495
+
496
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
497
+ `input_ids`.
498
+
499
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
500
+ [`PreTrainedTokenizer.__call__`] for details.
501
+
502
+ [What are input IDs?](../glossary#input-ids)
503
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
504
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
505
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
506
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
507
+
508
+ Two formats are allowed:
509
+ - a [`~cache_utils.Cache`] instance, see our
510
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
511
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
512
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
513
+ cache format.
514
+
515
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
516
+ legacy cache format will be returned.
517
+
518
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
519
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
520
+ of shape `(batch_size, sequence_length)`.
521
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
522
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
523
+
524
+ - 1 for tokens that are **not masked**,
525
+ - 0 for tokens that are **masked**.
526
+
527
+ [What are attention masks?](../glossary#attention-mask)
528
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
529
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
530
+
531
+ - 1 indicates the head is **not masked**,
532
+ - 0 indicates the head is **masked**.
533
+
534
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
535
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
536
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
537
+ model's internal embedding lookup matrix.
538
+
539
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
540
+ `past_key_values`).
541
+ use_cache (`bool`, *optional*):
542
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
543
+ `past_key_values`).
544
+ output_attentions (`bool`, *optional*):
545
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
546
+ tensors for more detail.
547
+ output_hidden_states (`bool`, *optional*):
548
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
549
+ more detail.
550
+ return_dict (`bool`, *optional*):
551
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
552
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
553
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
554
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
555
+ the complete sequence length.
556
+ """
557
+
558
+
559
+ @add_start_docstrings(
560
+ "The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.",
561
+ BLOOM_START_DOCSTRING,
562
+ )
563
+ class BloomModel(BloomPreTrainedModel):
564
+ def __init__(self, config: BloomConfig):
565
+ super().__init__(config)
566
+
567
+ self.embed_dim = config.hidden_size
568
+ self.num_heads = config.n_head
569
+
570
+ # Embedding + LN Embedding
571
+ self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
572
+ self.word_embeddings_layernorm = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
573
+
574
+ # Transformer blocks
575
+ self.h = nn.ModuleList([BloomBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
576
+
577
+ # Final Layer Norm
578
+ self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
579
+
580
+ self.gradient_checkpointing = False
581
+
582
+ # Initialize weights and apply final processing
583
+ self.post_init()
584
+
585
+ def build_alibi_tensor(self, attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
586
+ return build_alibi_tensor(attention_mask, num_heads, dtype)
587
+
588
+ def get_input_embeddings(self):
589
+ return self.word_embeddings
590
+
591
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
592
+ self.word_embeddings = new_embeddings
593
+
594
+ @add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
595
+ @add_code_sample_docstrings(
596
+ checkpoint=_CHECKPOINT_FOR_DOC,
597
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
598
+ config_class=_CONFIG_FOR_DOC,
599
+ )
600
+ def forward(
601
+ self,
602
+ input_ids: Optional[torch.LongTensor] = None,
603
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]] = None,
604
+ attention_mask: Optional[torch.Tensor] = None,
605
+ head_mask: Optional[torch.LongTensor] = None,
606
+ inputs_embeds: Optional[torch.LongTensor] = None,
607
+ use_cache: Optional[bool] = None,
608
+ output_attentions: Optional[bool] = None,
609
+ output_hidden_states: Optional[bool] = None,
610
+ return_dict: Optional[bool] = None,
611
+ cache_position: Optional[torch.LongTensor] = None,
612
+ **deprecated_arguments,
613
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
614
+ if deprecated_arguments.pop("position_ids", False) is not False:
615
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
616
+ warnings.warn(
617
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
618
+ " passing `position_ids`.",
619
+ FutureWarning,
620
+ )
621
+ if len(deprecated_arguments) > 0:
622
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
623
+
624
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
625
+ output_hidden_states = (
626
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
627
+ )
628
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
629
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
630
+
631
+ if (input_ids is None) ^ (inputs_embeds is not None):
632
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
633
+
634
+ if self.gradient_checkpointing and self.training and use_cache:
635
+ logger.warning_once(
636
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
637
+ )
638
+ use_cache = False
639
+
640
+ if inputs_embeds is None:
641
+ inputs_embeds = self.word_embeddings(input_ids)
642
+
643
+ # kept for BC (non `Cache` `past_key_values` inputs)
644
+ return_legacy_cache = False
645
+ if use_cache and not isinstance(past_key_values, Cache):
646
+ return_legacy_cache = True
647
+ if past_key_values is None:
648
+ past_key_values = DynamicCache()
649
+ else:
650
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
651
+ logger.warning_once(
652
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
653
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
654
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
655
+ )
656
+
657
+ batch_size, seq_length, _ = inputs_embeds.shape
658
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
659
+ seq_length_with_past = seq_length + past_length
660
+ if cache_position is None:
661
+ cache_position = torch.arange(past_length, past_length + seq_length, device=inputs_embeds.device)
662
+
663
+ # Prepare head mask if needed
664
+ # 1.0 in head_mask indicate we keep the head
665
+ # attention_probs has shape batch_size x num_heads x N x N
666
+ # head_mask has shape n_layer x batch x num_heads x N x N
667
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
668
+ hidden_states = self.word_embeddings_layernorm(inputs_embeds)
669
+
670
+ next_decoder_cache = None
671
+ all_self_attentions = () if output_attentions else None
672
+ all_hidden_states = () if output_hidden_states else None
673
+
674
+ # Compute alibi tensor: check build_alibi_tensor documentation
675
+ if attention_mask is None:
676
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
677
+ else:
678
+ attention_mask = attention_mask.to(hidden_states.device)
679
+
680
+ alibi = self.build_alibi_tensor(attention_mask, self.num_heads, dtype=hidden_states.dtype)
681
+ causal_mask = self._update_causal_mask(
682
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
683
+ )
684
+
685
+ for i, block in enumerate(self.h):
686
+ if output_hidden_states:
687
+ all_hidden_states = all_hidden_states + (hidden_states,)
688
+
689
+ if self.gradient_checkpointing and self.training:
690
+ outputs = self._gradient_checkpointing_func(
691
+ block.__call__,
692
+ hidden_states,
693
+ alibi,
694
+ causal_mask,
695
+ past_key_values,
696
+ head_mask[i],
697
+ use_cache,
698
+ output_attentions,
699
+ cache_position,
700
+ )
701
+ else:
702
+ outputs = block(
703
+ hidden_states,
704
+ layer_past=past_key_values,
705
+ attention_mask=causal_mask,
706
+ head_mask=head_mask[i],
707
+ use_cache=use_cache,
708
+ output_attentions=output_attentions,
709
+ alibi=alibi,
710
+ cache_position=cache_position,
711
+ )
712
+
713
+ hidden_states = outputs[0]
714
+ if use_cache:
715
+ next_decoder_cache = outputs[1]
716
+
717
+ if output_attentions:
718
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
719
+
720
+ # Add last hidden state
721
+ hidden_states = self.ln_f(hidden_states)
722
+
723
+ if output_hidden_states:
724
+ all_hidden_states = all_hidden_states + (hidden_states,)
725
+
726
+ next_cache = next_decoder_cache if use_cache else None
727
+ if return_legacy_cache:
728
+ next_cache = next_cache.to_legacy_cache()
729
+
730
+ if not return_dict:
731
+ return tuple(
732
+ v for v in [hidden_states, next_cache, all_hidden_states, all_self_attentions] if v is not None
733
+ )
734
+
735
+ return BaseModelOutputWithPastAndCrossAttentions(
736
+ last_hidden_state=hidden_states,
737
+ past_key_values=next_cache,
738
+ hidden_states=all_hidden_states,
739
+ attentions=all_self_attentions,
740
+ )
741
+
742
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
743
+ def _update_causal_mask(
744
+ self,
745
+ attention_mask: torch.Tensor,
746
+ input_tensor: torch.Tensor,
747
+ cache_position: torch.Tensor,
748
+ past_key_values: Cache,
749
+ output_attentions: bool = False,
750
+ ):
751
+ if self.config._attn_implementation == "flash_attention_2":
752
+ if attention_mask is not None and (attention_mask == 0.0).any():
753
+ return attention_mask
754
+ return None
755
+ if self.config._attn_implementation == "flex_attention":
756
+ if isinstance(attention_mask, torch.Tensor):
757
+ attention_mask = make_flex_block_causal_mask(attention_mask)
758
+ if isinstance(attention_mask, BlockMask):
759
+ return attention_mask
760
+
761
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
762
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
763
+ # to infer the attention mask.
764
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
765
+ using_static_cache = isinstance(past_key_values, StaticCache)
766
+
767
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
768
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
769
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
770
+ attention_mask,
771
+ inputs_embeds=input_tensor,
772
+ past_key_values_length=past_seen_tokens,
773
+ is_training=self.training,
774
+ ):
775
+ return None
776
+
777
+ dtype, device = input_tensor.dtype, input_tensor.device
778
+ sequence_length = input_tensor.shape[1]
779
+ if using_static_cache:
780
+ target_length = past_key_values.get_max_cache_shape()
781
+ else:
782
+ target_length = (
783
+ attention_mask.shape[-1]
784
+ if isinstance(attention_mask, torch.Tensor)
785
+ else past_seen_tokens + sequence_length + 1
786
+ )
787
+
788
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
789
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
790
+ attention_mask,
791
+ sequence_length=sequence_length,
792
+ target_length=target_length,
793
+ dtype=dtype,
794
+ device=device,
795
+ cache_position=cache_position,
796
+ batch_size=input_tensor.shape[0],
797
+ )
798
+
799
+ if (
800
+ self.config._attn_implementation == "sdpa"
801
+ and attention_mask is not None
802
+ and attention_mask.device.type in ["cuda", "xpu"]
803
+ and not output_attentions
804
+ ):
805
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
806
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
807
+ # Details: https://github.com/pytorch/pytorch/issues/110213
808
+ min_dtype = torch.finfo(dtype).min
809
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
810
+
811
+ return causal_mask
812
+
813
+ @staticmethod
814
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._prepare_4d_causal_attention_mask_with_cache_position
815
+ def _prepare_4d_causal_attention_mask_with_cache_position(
816
+ attention_mask: torch.Tensor,
817
+ sequence_length: int,
818
+ target_length: int,
819
+ dtype: torch.dtype,
820
+ device: torch.device,
821
+ cache_position: torch.Tensor,
822
+ batch_size: int,
823
+ **kwargs,
824
+ ):
825
+ """
826
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
827
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
828
+
829
+ Args:
830
+ attention_mask (`torch.Tensor`):
831
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
832
+ `(batch_size, 1, query_length, key_value_length)`.
833
+ sequence_length (`int`):
834
+ The sequence length being processed.
835
+ target_length (`int`):
836
+ The target length: when generating with static cache, the mask should be as long as the static cache,
837
+ to account for the 0 padding, the part of the cache that is not filled yet.
838
+ dtype (`torch.dtype`):
839
+ The dtype to use for the 4D attention mask.
840
+ device (`torch.device`):
841
+ The device to place the 4D attention mask on.
842
+ cache_position (`torch.Tensor`):
843
+ Indices depicting the position of the input sequence tokens in the sequence.
844
+ batch_size (`torch.Tensor`):
845
+ Batch size.
846
+ """
847
+ if attention_mask is not None and attention_mask.dim() == 4:
848
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
849
+ causal_mask = attention_mask
850
+ else:
851
+ min_dtype = torch.finfo(dtype).min
852
+ causal_mask = torch.full(
853
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
854
+ )
855
+ if sequence_length != 1:
856
+ causal_mask = torch.triu(causal_mask, diagonal=1)
857
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
858
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
859
+ if attention_mask is not None:
860
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
861
+ mask_length = attention_mask.shape[-1]
862
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
863
+ causal_mask.device
864
+ )
865
+ padding_mask = padding_mask == 0
866
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
867
+ padding_mask, min_dtype
868
+ )
869
+
870
+ return causal_mask
871
+
872
+
873
+ @add_start_docstrings(
874
+ """
875
+ The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
876
+ embeddings).
877
+ """,
878
+ BLOOM_START_DOCSTRING,
879
+ )
880
+ class BloomForCausalLM(BloomPreTrainedModel, GenerationMixin):
881
+ _tied_weights_keys = ["lm_head.weight"]
882
+
883
+ def __init__(self, config: BloomConfig):
884
+ super().__init__(config)
885
+ self.transformer = BloomModel(config)
886
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
887
+
888
+ # Initialize weights and apply final processing
889
+ self.post_init()
890
+
891
+ def get_output_embeddings(self):
892
+ return self.lm_head
893
+
894
+ def set_output_embeddings(self, new_embeddings: torch.Tensor):
895
+ self.lm_head = new_embeddings
896
+
897
+ def prepare_inputs_for_generation(
898
+ self,
899
+ input_ids,
900
+ past_key_values=None,
901
+ attention_mask=None,
902
+ inputs_embeds=None,
903
+ cache_position=None,
904
+ use_cache=True,
905
+ **kwargs,
906
+ ):
907
+ # Overwriten because of the fixed-shape attention mask creation
908
+
909
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
910
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
911
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
912
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
913
+ # (we can't check exception 3 while compiling)
914
+ # Exception 4: If input_embeds are passed then slice it through `cache_position`, to keep only the unprocessed tokens and
915
+ # generate the first token for each sequence. Later use the generated Input ids for continuation.
916
+ if past_key_values is not None:
917
+ if inputs_embeds is not None and input_ids.shape[1] == 0: # Exception 4
918
+ inputs_embeds = inputs_embeds[:, -cache_position.shape[0] :]
919
+ elif (
920
+ inputs_embeds is not None # Exception 1
921
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
922
+ ):
923
+ input_ids = input_ids[:, -cache_position.shape[0] :]
924
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
925
+ input_ids = input_ids[:, cache_position]
926
+
927
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
928
+ if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:
929
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
930
+ else:
931
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the
932
+ # input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in
933
+ # the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
934
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
935
+
936
+ # This part differs from other models because BLOOM needs a 2D mask to construct alibi tensor
937
+ # The only difference is the usage of 2D instead of 4D mask, but the shape will be static
938
+ if isinstance(past_key_values, StaticCache) and attention_mask is not None:
939
+ target_length = past_key_values.get_max_cache_shape()
940
+ batch_size, seq_length = attention_mask.shape
941
+ diff = target_length - seq_length
942
+
943
+ new_attn_mask = torch.zeros(batch_size, diff, device=attention_mask.device, dtype=attention_mask.dtype)
944
+ attention_mask = torch.cat(
945
+ [attention_mask, new_attn_mask],
946
+ dim=-1,
947
+ )
948
+
949
+ model_inputs.update(
950
+ {
951
+ "cache_position": cache_position,
952
+ "past_key_values": past_key_values,
953
+ "use_cache": use_cache,
954
+ "attention_mask": attention_mask,
955
+ }
956
+ )
957
+ return model_inputs
958
+
959
+ @add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
960
+ @add_code_sample_docstrings(
961
+ checkpoint=_CHECKPOINT_FOR_DOC,
962
+ output_type=CausalLMOutputWithCrossAttentions,
963
+ config_class=_CONFIG_FOR_DOC,
964
+ )
965
+ def forward(
966
+ self,
967
+ input_ids: Optional[torch.LongTensor] = None,
968
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]] = None,
969
+ attention_mask: Optional[torch.Tensor] = None,
970
+ head_mask: Optional[torch.Tensor] = None,
971
+ inputs_embeds: Optional[torch.Tensor] = None,
972
+ labels: Optional[torch.Tensor] = None,
973
+ use_cache: Optional[bool] = None,
974
+ output_attentions: Optional[bool] = None,
975
+ output_hidden_states: Optional[bool] = None,
976
+ return_dict: Optional[bool] = None,
977
+ cache_position: Optional[torch.LongTensor] = None,
978
+ **deprecated_arguments,
979
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
980
+ r"""
981
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
982
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
983
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
984
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
985
+ """
986
+ # Bloom has deprecated kwargs, so we need to pop num_items_in_batch explicitly
987
+ num_items_in_batch = deprecated_arguments.pop("num_items_in_batch", None)
988
+ if deprecated_arguments.pop("position_ids", False) is not False:
989
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
990
+ warnings.warn(
991
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
992
+ " passing `position_ids`.",
993
+ FutureWarning,
994
+ )
995
+ if len(deprecated_arguments) > 0:
996
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
997
+
998
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
999
+
1000
+ transformer_outputs = self.transformer(
1001
+ input_ids,
1002
+ past_key_values=past_key_values,
1003
+ attention_mask=attention_mask,
1004
+ head_mask=head_mask,
1005
+ inputs_embeds=inputs_embeds,
1006
+ use_cache=use_cache,
1007
+ output_attentions=output_attentions,
1008
+ output_hidden_states=output_hidden_states,
1009
+ return_dict=return_dict,
1010
+ cache_position=cache_position,
1011
+ )
1012
+ hidden_states = transformer_outputs[0]
1013
+
1014
+ lm_logits = self.lm_head(hidden_states)
1015
+
1016
+ loss = None
1017
+ if labels is not None:
1018
+ # move labels to correct device to enable model parallelism
1019
+ labels = labels.to(lm_logits.device)
1020
+ # Flatten the tokens
1021
+ loss = self.loss_function(
1022
+ lm_logits,
1023
+ labels,
1024
+ vocab_size=self.config.vocab_size,
1025
+ num_items_in_batch=num_items_in_batch,
1026
+ )
1027
+
1028
+ if not return_dict:
1029
+ output = (lm_logits,) + transformer_outputs[1:]
1030
+ return ((loss,) + output) if loss is not None else output
1031
+
1032
+ return CausalLMOutputWithCrossAttentions(
1033
+ loss=loss,
1034
+ logits=lm_logits,
1035
+ past_key_values=transformer_outputs.past_key_values,
1036
+ hidden_states=transformer_outputs.hidden_states,
1037
+ attentions=transformer_outputs.attentions,
1038
+ )
1039
+
1040
+ def _reorder_cache(
1041
+ self, past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
1042
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
1043
+ """
1044
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1045
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1046
+ beam_idx at every generation step.
1047
+
1048
+ Output shares the same memory storage as `past`.
1049
+ """
1050
+ # Get a copy of `beam_idx` on all the devices where we need those indices.
1051
+ device_to_beam_idx = {
1052
+ past_state.device: beam_idx.to(past_state.device) for layer_past in past for past_state in layer_past
1053
+ }
1054
+ reordered_past = tuple(
1055
+ (
1056
+ layer_past[0].index_select(0, device_to_beam_idx[layer_past[0].device]),
1057
+ layer_past[1].index_select(0, device_to_beam_idx[layer_past[0].device]),
1058
+ )
1059
+ for layer_past in past
1060
+ )
1061
+ return reordered_past
1062
+
1063
+
1064
+ @add_start_docstrings(
1065
+ """
1066
+ The Bloom Model transformer with a sequence classification head on top (linear layer).
1067
+
1068
+ [`BloomForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1069
+ (e.g. GPT-1) do.
1070
+
1071
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1072
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1073
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1074
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1075
+ each row of the batch).
1076
+ """,
1077
+ BLOOM_START_DOCSTRING,
1078
+ )
1079
+ class BloomForSequenceClassification(BloomPreTrainedModel):
1080
+ def __init__(self, config: BloomConfig):
1081
+ super().__init__(config)
1082
+ self.num_labels = config.num_labels
1083
+ self.transformer = BloomModel(config)
1084
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
1085
+
1086
+ # Initialize weights and apply final processing
1087
+ self.post_init()
1088
+
1089
+ @add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
1090
+ @add_code_sample_docstrings(
1091
+ checkpoint=_CHECKPOINT_FOR_DOC,
1092
+ output_type=SequenceClassifierOutputWithPast,
1093
+ config_class=_CONFIG_FOR_DOC,
1094
+ )
1095
+ def forward(
1096
+ self,
1097
+ input_ids: Optional[torch.LongTensor] = None,
1098
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]] = None,
1099
+ attention_mask: Optional[torch.Tensor] = None,
1100
+ head_mask: Optional[torch.Tensor] = None,
1101
+ inputs_embeds: Optional[torch.Tensor] = None,
1102
+ labels: Optional[torch.Tensor] = None,
1103
+ use_cache: Optional[bool] = None,
1104
+ output_attentions: Optional[bool] = None,
1105
+ output_hidden_states: Optional[bool] = None,
1106
+ return_dict: Optional[bool] = None,
1107
+ **deprecated_arguments,
1108
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
1109
+ r"""
1110
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1111
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1112
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1113
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1114
+ """
1115
+ if deprecated_arguments.pop("position_ids", False) is not False:
1116
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
1117
+ warnings.warn(
1118
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
1119
+ " passing `position_ids`.",
1120
+ FutureWarning,
1121
+ )
1122
+ if len(deprecated_arguments) > 0:
1123
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
1124
+
1125
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1126
+
1127
+ transformer_outputs = self.transformer(
1128
+ input_ids,
1129
+ past_key_values=past_key_values,
1130
+ attention_mask=attention_mask,
1131
+ head_mask=head_mask,
1132
+ inputs_embeds=inputs_embeds,
1133
+ use_cache=use_cache,
1134
+ output_attentions=output_attentions,
1135
+ output_hidden_states=output_hidden_states,
1136
+ return_dict=return_dict,
1137
+ )
1138
+
1139
+ hidden_states = transformer_outputs[0]
1140
+ logits = self.score(hidden_states)
1141
+
1142
+ if input_ids is not None:
1143
+ batch_size = input_ids.shape[0]
1144
+ else:
1145
+ batch_size = inputs_embeds.shape[0]
1146
+
1147
+ if self.config.pad_token_id is None and batch_size != 1:
1148
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1149
+ if self.config.pad_token_id is None:
1150
+ last_non_pad_token = -1
1151
+ elif input_ids is not None:
1152
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1153
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
1154
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
1155
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1156
+ else:
1157
+ last_non_pad_token = -1
1158
+ logger.warning_once(
1159
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1160
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1161
+ )
1162
+
1163
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
1164
+
1165
+ loss = None
1166
+ if labels is not None:
1167
+ if self.config.problem_type is None:
1168
+ if self.num_labels == 1:
1169
+ self.config.problem_type = "regression"
1170
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1171
+ self.config.problem_type = "single_label_classification"
1172
+ else:
1173
+ self.config.problem_type = "multi_label_classification"
1174
+
1175
+ if self.config.problem_type == "regression":
1176
+ loss_fct = MSELoss()
1177
+ if self.num_labels == 1:
1178
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1179
+ else:
1180
+ loss = loss_fct(pooled_logits, labels)
1181
+ elif self.config.problem_type == "single_label_classification":
1182
+ loss_fct = CrossEntropyLoss()
1183
+ loss = loss_fct(pooled_logits, labels)
1184
+ elif self.config.problem_type == "multi_label_classification":
1185
+ loss_fct = BCEWithLogitsLoss()
1186
+ loss = loss_fct(pooled_logits, labels)
1187
+ if not return_dict:
1188
+ output = (pooled_logits,) + transformer_outputs[1:]
1189
+ return ((loss,) + output) if loss is not None else output
1190
+
1191
+ return SequenceClassifierOutputWithPast(
1192
+ loss=loss,
1193
+ logits=pooled_logits,
1194
+ past_key_values=transformer_outputs.past_key_values,
1195
+ hidden_states=transformer_outputs.hidden_states,
1196
+ attentions=transformer_outputs.attentions,
1197
+ )
1198
+
1199
+
1200
+ @add_start_docstrings(
1201
+ """
1202
+ Bloom Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1203
+ Named-Entity-Recognition (NER) tasks.
1204
+ """,
1205
+ BLOOM_START_DOCSTRING,
1206
+ )
1207
+ class BloomForTokenClassification(BloomPreTrainedModel):
1208
+ def __init__(self, config: BloomConfig):
1209
+ super().__init__(config)
1210
+ self.num_labels = config.num_labels
1211
+
1212
+ self.transformer = BloomModel(config)
1213
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1214
+ classifier_dropout = config.classifier_dropout
1215
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1216
+ classifier_dropout = config.hidden_dropout
1217
+ else:
1218
+ classifier_dropout = 0.1
1219
+ self.dropout = nn.Dropout(classifier_dropout)
1220
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1221
+
1222
+ # Initialize weights and apply final processing
1223
+ self.post_init()
1224
+
1225
+ @add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
1226
+ @add_code_sample_docstrings(
1227
+ checkpoint=_CHECKPOINT_FOR_DOC,
1228
+ output_type=TokenClassifierOutput,
1229
+ config_class=_CONFIG_FOR_DOC,
1230
+ )
1231
+ def forward(
1232
+ self,
1233
+ input_ids: Optional[torch.LongTensor] = None,
1234
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.Tensor, torch.Tensor], ...]]] = None,
1235
+ attention_mask: Optional[torch.Tensor] = None,
1236
+ head_mask: Optional[torch.Tensor] = None,
1237
+ inputs_embeds: Optional[torch.Tensor] = None,
1238
+ labels: Optional[torch.Tensor] = None,
1239
+ use_cache: Optional[bool] = None,
1240
+ output_attentions: Optional[bool] = None,
1241
+ output_hidden_states: Optional[bool] = None,
1242
+ return_dict: Optional[bool] = None,
1243
+ **deprecated_arguments,
1244
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1245
+ r"""
1246
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1247
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1248
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1249
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1250
+ """
1251
+ if deprecated_arguments.pop("position_ids", False) is not False:
1252
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
1253
+ warnings.warn(
1254
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
1255
+ " passing `position_ids`.",
1256
+ FutureWarning,
1257
+ )
1258
+ if len(deprecated_arguments) > 0:
1259
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
1260
+
1261
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1262
+
1263
+ transformer_outputs = self.transformer(
1264
+ input_ids,
1265
+ past_key_values=past_key_values,
1266
+ attention_mask=attention_mask,
1267
+ head_mask=head_mask,
1268
+ inputs_embeds=inputs_embeds,
1269
+ use_cache=use_cache,
1270
+ output_attentions=output_attentions,
1271
+ output_hidden_states=output_hidden_states,
1272
+ return_dict=return_dict,
1273
+ )
1274
+
1275
+ hidden_states = transformer_outputs[0]
1276
+ hidden_states = self.dropout(hidden_states)
1277
+ logits = self.classifier(hidden_states)
1278
+
1279
+ loss = None
1280
+ if labels is not None:
1281
+ # move labels to correct device to enable model parallelism
1282
+ labels = labels.to(logits.device)
1283
+ batch_size, seq_length = labels.shape
1284
+ loss_fct = CrossEntropyLoss()
1285
+ loss = loss_fct(
1286
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1287
+ )
1288
+
1289
+ if not return_dict:
1290
+ output = (logits,) + transformer_outputs[2:]
1291
+ return ((loss,) + output) if loss is not None else output
1292
+
1293
+ return TokenClassifierOutput(
1294
+ loss=loss,
1295
+ logits=logits,
1296
+ hidden_states=transformer_outputs.hidden_states,
1297
+ attentions=transformer_outputs.attentions,
1298
+ )
1299
+
1300
+
1301
+ @add_start_docstrings(
1302
+ """
1303
+ The BLOOM Model transformer with a span classification head on top for extractive question-answering tasks like
1304
+ SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1305
+ """,
1306
+ BLOOM_START_DOCSTRING,
1307
+ )
1308
+ class BloomForQuestionAnswering(BloomPreTrainedModel):
1309
+ def __init__(self, config):
1310
+ super().__init__(config)
1311
+ self.transformer = BloomModel(config)
1312
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1313
+
1314
+ # Initialize weights and apply final processing
1315
+ self.post_init()
1316
+
1317
+ @add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1318
+ def forward(
1319
+ self,
1320
+ input_ids: Optional[torch.LongTensor] = None,
1321
+ attention_mask: Optional[torch.FloatTensor] = None,
1322
+ position_ids: Optional[torch.LongTensor] = None,
1323
+ head_mask: Optional[torch.FloatTensor] = None,
1324
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1325
+ start_positions: Optional[torch.LongTensor] = None,
1326
+ end_positions: Optional[torch.LongTensor] = None,
1327
+ output_attentions: Optional[bool] = None,
1328
+ output_hidden_states: Optional[bool] = None,
1329
+ return_dict: Optional[bool] = None,
1330
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1331
+ r"""
1332
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1333
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1334
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1335
+ are not taken into account for computing the loss.
1336
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1337
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1338
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1339
+ are not taken into account for computing the loss.
1340
+ """
1341
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1342
+
1343
+ outputs = self.transformer(
1344
+ input_ids,
1345
+ attention_mask=attention_mask,
1346
+ position_ids=position_ids,
1347
+ head_mask=head_mask,
1348
+ inputs_embeds=inputs_embeds,
1349
+ output_attentions=output_attentions,
1350
+ output_hidden_states=output_hidden_states,
1351
+ return_dict=return_dict,
1352
+ )
1353
+
1354
+ sequence_output = outputs[0]
1355
+
1356
+ logits = self.qa_outputs(sequence_output)
1357
+ start_logits, end_logits = logits.split(1, dim=-1)
1358
+ start_logits = start_logits.squeeze(-1).contiguous()
1359
+ end_logits = end_logits.squeeze(-1).contiguous()
1360
+
1361
+ total_loss = None
1362
+ if start_positions is not None and end_positions is not None:
1363
+ # If we are on multi-GPU, split add a dimension
1364
+ if len(start_positions.size()) > 1:
1365
+ start_positions = start_positions.squeeze(-1)
1366
+ if len(end_positions.size()) > 1:
1367
+ end_positions = end_positions.squeeze(-1)
1368
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1369
+ ignored_index = start_logits.size(1)
1370
+ start_positions = start_positions.clamp(0, ignored_index)
1371
+ end_positions = end_positions.clamp(0, ignored_index)
1372
+
1373
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1374
+ start_loss = loss_fct(start_logits, start_positions)
1375
+ end_loss = loss_fct(end_logits, end_positions)
1376
+ total_loss = (start_loss + end_loss) / 2
1377
+
1378
+ if not return_dict:
1379
+ output = (start_logits, end_logits) + outputs[2:]
1380
+ return ((total_loss,) + output) if total_loss is not None else output
1381
+
1382
+ return QuestionAnsweringModelOutput(
1383
+ loss=total_loss,
1384
+ start_logits=start_logits,
1385
+ end_logits=end_logits,
1386
+ hidden_states=outputs.hidden_states,
1387
+ attentions=outputs.attentions,
1388
+ )
1389
+
1390
+
1391
+ __all__ = [
1392
+ "BloomForCausalLM",
1393
+ "BloomModel",
1394
+ "BloomPreTrainedModel",
1395
+ "BloomForSequenceClassification",
1396
+ "BloomForTokenClassification",
1397
+ "BloomForQuestionAnswering",
1398
+ ]
vllm/lib/python3.10/site-packages/transformers/models/bloom/tokenization_bloom_fast.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Bloom."""
16
+
17
+ import pickle
18
+ from typing import Optional, Tuple
19
+
20
+ from ...tokenization_utils_base import BatchEncoding
21
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
28
+
29
+
30
+ class BloomTokenizerFast(PreTrainedTokenizerFast):
31
+ """
32
+ Construct a "fast" Bloom tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
33
+ Byte-Pair-Encoding.
34
+
35
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
36
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
37
+
38
+ ```python
39
+ >>> from transformers import BloomTokenizerFast
40
+
41
+ >>> tokenizer = BloomTokenizerFast.from_pretrained("bigscience/bloom")
42
+ >>> tokenizer("Hello world")["input_ids"]
43
+ [59414, 8876]
44
+
45
+ >>> tokenizer(" Hello world")["input_ids"]
46
+ [86153, 8876]
47
+ ```
48
+
49
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
50
+ the model was not pretrained this way, it might yield a decrease in performance.
51
+
52
+ <Tip>
53
+
54
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
55
+
56
+ </Tip>
57
+
58
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
59
+ refer to this superclass for more information regarding those methods.
60
+
61
+ Args:
62
+ vocab_file (`str`):
63
+ Path to the vocabulary file.
64
+ merges_file (`str`):
65
+ Path to the merges file.
66
+ errors (`str`, *optional*, defaults to `"replace"`):
67
+ Paradigm to follow when decoding bytes to UTF-8. See
68
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
69
+ unk_token (`str`, *optional*, defaults to `<|endoftext|>`):
70
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
71
+ token instead.
72
+ bos_token (`str`, *optional*, defaults to `<|endoftext|>`):
73
+ The beginning of sequence token.
74
+ eos_token (`str`, *optional*, defaults to `<|endoftext|>`):
75
+ The end of sequence token.
76
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
77
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
78
+ other word. (Bloom tokenizer detect beginning of words by the preceding space).
79
+ trim_offsets (`bool`, *optional*, defaults to `True`):
80
+ Whether or not the post-processing step should trim offsets to avoid including whitespaces.
81
+ """
82
+
83
+ vocab_files_names = VOCAB_FILES_NAMES
84
+ model_input_names = ["input_ids", "attention_mask"]
85
+ slow_tokenizer_class = None
86
+ # No `max_model_input_sizes` as BLOOM uses ALiBi positional embeddings
87
+
88
+ def __init__(
89
+ self,
90
+ vocab_file=None,
91
+ merges_file=None,
92
+ tokenizer_file=None,
93
+ unk_token="<unk>",
94
+ bos_token="<s>",
95
+ eos_token="</s>",
96
+ pad_token="<pad>",
97
+ add_prefix_space=False,
98
+ clean_up_tokenization_spaces=False,
99
+ **kwargs,
100
+ ):
101
+ super().__init__(
102
+ vocab_file=vocab_file,
103
+ merges_file=merges_file,
104
+ tokenizer_file=tokenizer_file,
105
+ unk_token=unk_token,
106
+ bos_token=bos_token,
107
+ eos_token=eos_token,
108
+ pad_token=pad_token,
109
+ add_prefix_space=add_prefix_space,
110
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
111
+ **kwargs,
112
+ )
113
+ # TODO @ArthurZucker this can only work one way for now, to update later-on. Tests should also properly
114
+ # check this as they were green before.
115
+ pre_tok_state = pickle.dumps(self.backend_tokenizer.pre_tokenizer)
116
+ decoder_state = pickle.dumps(self.backend_tokenizer.decoder)
117
+
118
+ if add_prefix_space:
119
+ pre_tok_state = pre_tok_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
120
+ decoder_state = decoder_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
121
+ self.backend_tokenizer.pre_tokenizer = pickle.loads(pre_tok_state)
122
+ self.backend_tokenizer.decoder = pickle.loads(decoder_state)
123
+
124
+ self.add_prefix_space = add_prefix_space
125
+
126
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
127
+ is_split_into_words = kwargs.get("is_split_into_words", False)
128
+ if not (self.add_prefix_space or not is_split_into_words):
129
+ raise Exception(
130
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
131
+ " pretokenized inputs."
132
+ )
133
+
134
+ return super()._batch_encode_plus(*args, **kwargs)
135
+
136
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
137
+ is_split_into_words = kwargs.get("is_split_into_words", False)
138
+
139
+ if not (self.add_prefix_space or not is_split_into_words):
140
+ raise Exception(
141
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
142
+ " pretokenized inputs."
143
+ )
144
+
145
+ return super()._encode_plus(*args, **kwargs)
146
+
147
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
148
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
149
+ return tuple(files)
150
+
151
+
152
+ __all__ = ["BloomTokenizerFast"]
vllm/lib/python3.10/site-packages/transformers/models/cpmant/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_cpmant import *
22
+ from .modeling_cpmant import *
23
+ from .tokenization_cpmant import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (567 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-310.pyc ADDED
Binary file (4.61 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-310.pyc ADDED
Binary file (9.56 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/cpmant/modeling_cpmant.py ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The OpenBMB Team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch CPMAnt"""
16
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn.functional as F
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
31
+ from .configuration_cpmant import CpmAntConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+ _CHECKPOINT_FOR_DOC = "openbmb/cpm-ant-10b"
37
+ _CONFIG_FOR_DOC = "CpmAntConfig"
38
+
39
+
40
+ class CpmAntLayerNorm(nn.Module):
41
+ """
42
+ We use Root Mean Square (RMS) Layer Normalization, please see https://arxiv.org/abs/1910.07467 for details."
43
+ """
44
+
45
+ def __init__(self, config: CpmAntConfig):
46
+ super().__init__()
47
+
48
+ self.eps = config.eps
49
+ self.dim_norm = config.hidden_size
50
+ self.weight = nn.Parameter(torch.empty(config.hidden_size))
51
+
52
+ def forward(self, hidden_states: torch.Tensor):
53
+ """
54
+ Args:
55
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
56
+ """
57
+ if hidden_states.size(-1) != self.dim_norm:
58
+ raise AssertionError("hidden_states.size(-1) != self.dim_norm")
59
+ old_dtype = hidden_states.dtype
60
+ variance = hidden_states.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
61
+ hidden_states = (hidden_states * torch.rsqrt(variance + self.eps)).to(old_dtype) * self.weight
62
+ return hidden_states
63
+
64
+
65
+ class CpmAntAttention(nn.Module):
66
+ def __init__(self, config: CpmAntConfig):
67
+ super().__init__()
68
+ self.dim_model = config.hidden_size
69
+ self.num_heads = config.num_attention_heads
70
+ self.dim_head = config.dim_head
71
+
72
+ self.project_q = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
73
+ self.project_k = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
74
+ self.project_v = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
75
+
76
+ self.attention_out = nn.Linear(self.num_heads * self.dim_head, self.dim_model, bias=False)
77
+
78
+ self.softmax = torch.nn.Softmax(dim=-1)
79
+
80
+ if config.dropout_p is not None:
81
+ self.dropout = torch.nn.Dropout(p=config.dropout_p)
82
+ else:
83
+ self.dropout = None
84
+
85
+ def forward(
86
+ self,
87
+ hidden_q: torch.Tensor,
88
+ hidden_kv: torch.Tensor,
89
+ attention_mask: torch.BoolTensor,
90
+ position_bias: torch.Tensor,
91
+ output_attentions: Optional[bool] = False,
92
+ past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
93
+ use_cache: Optional[bool] = None,
94
+ ):
95
+ """
96
+ Args:
97
+ hidden_q (`torch.Tensor`):
98
+ Input of transformer block(self-attention block). It can be the raw embedding of a batch of sequences.
99
+ hidden_kv (`torch.Tensor` of shape `(batch, len_k, dim_model)`)):
100
+ Tensor *key_value* and *query* of shape `(batch, len_k, dim_model)`
101
+ attention_mask (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
102
+ Avoid invalid areas to participate in the calculation of self-attention.
103
+ position_bias (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
104
+ Provide positional information to self-attention block.
105
+ output_attentions (`bool`, *optional*):
106
+ Whether or not to return the attentions tensors of all attention layers.
107
+ past_key_values (`Tuple[torch.Tensor, torch.Tensor]`, *optional*):
108
+ Cached past key and value projection states.
109
+ use_cache (`bool`, *optional*):
110
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
111
+ (see `past_key_values`).
112
+ """
113
+ batch_size = hidden_q.size(0)
114
+ len_q = hidden_q.size(1)
115
+ len_k = hidden_kv.size(1)
116
+
117
+ query = self.project_q(hidden_q)
118
+ key = self.project_k(hidden_kv)
119
+ value = self.project_v(hidden_kv)
120
+
121
+ query = query.view(batch_size, len_q, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
122
+ key = key.view(batch_size, len_k, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
123
+ value = value.view(batch_size, len_k, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
124
+
125
+ if past_key_values is not None:
126
+ key = torch.cat([past_key_values[0], key], dim=-2)
127
+ value = torch.cat([past_key_values[1], value], dim=-2)
128
+ len_k = key.size(-2)
129
+
130
+ # (batch_size, num_heads, len_q, dim_head) @ (batch_size, num_heads, dim_head, len_k) -> (batch_size, num_heads, len_q, len_k)
131
+ score = torch.matmul(query, key.transpose(-1, -2)) / math.sqrt(self.dim_head)
132
+ score = score + position_bias
133
+
134
+ score = torch.masked_fill(
135
+ score,
136
+ attention_mask.view(batch_size, 1, len_q, len_k) == torch.tensor(False),
137
+ torch.scalar_tensor(float("-inf"), device=score.device, dtype=score.dtype),
138
+ )
139
+ score = self.softmax(score)
140
+
141
+ score = torch.masked_fill(
142
+ score,
143
+ attention_mask.view(batch_size, 1, len_q, len_k) == torch.tensor(False),
144
+ torch.scalar_tensor(0, device=score.device, dtype=score.dtype),
145
+ )
146
+ if output_attentions:
147
+ attn_weights = score
148
+ else:
149
+ attn_weights = None
150
+
151
+ if self.dropout is not None:
152
+ score = self.dropout(score)
153
+
154
+ # (batch_size, num_heads, len_q, len_k) @ (batch_size, num_heads, len_k, dim_head) -> (batch_size, num_heads, len_q, dim_head)
155
+ score = torch.matmul(score, value)
156
+
157
+ score = score.view(batch_size, self.num_heads, len_q, self.dim_head).permute(0, 2, 1, 3)
158
+ score = score.contiguous().view(batch_size, len_q, self.num_heads * self.dim_head)
159
+
160
+ score = self.attention_out(score)
161
+
162
+ past_key_values = None
163
+ if use_cache:
164
+ past_key_values = (key, value)
165
+
166
+ return score, attn_weights, past_key_values
167
+
168
+
169
+ class CpmAntSelfAttentionBlock(nn.Module):
170
+ def __init__(self, config: CpmAntConfig):
171
+ super().__init__()
172
+ self.layernorm_before_attention = CpmAntLayerNorm(config)
173
+ self.self_attention = CpmAntAttention(config)
174
+ if config.dropout_p:
175
+ self.dropout = torch.nn.Dropout(config.dropout_p)
176
+ else:
177
+ self.dropout = None
178
+
179
+ def forward(
180
+ self,
181
+ hidden_states: torch.Tensor,
182
+ attention_mask: torch.Tensor,
183
+ position_bias: Optional[torch.Tensor] = None,
184
+ output_attentions: Optional[bool] = False,
185
+ past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
186
+ use_cache: Optional[bool] = None,
187
+ ):
188
+ """
189
+ Args:
190
+ hidden_states (`torch.Tensor` of shape `(batch, len_seq, dim_model)`):
191
+ Input of transformer block(self-attention block). It can be the raw embedding of a batch of sequences.
192
+ attention_mask (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
193
+ Avoid invalid areas to participate in the calculation of self-attention.
194
+ position_bias (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
195
+ Provide positional information to self-attention block.
196
+ output_attentions (`bool`, *optional*):
197
+ Whether or not to return the attentions tensors of all attention layers.
198
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*):
199
+ Cached past key and value projection states.
200
+ use_cache (`bool`, *optional*):
201
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
202
+ (see `past_key_values`).
203
+ """
204
+ outputs = self.layernorm_before_attention(hidden_states)
205
+ outputs = self.self_attention(
206
+ outputs, outputs, attention_mask, position_bias, output_attentions, past_key_values, use_cache
207
+ )
208
+
209
+ outputs, attn_weights, current_key_value = outputs
210
+
211
+ if self.dropout is not None:
212
+ outputs = self.dropout(outputs)
213
+ hidden_states = hidden_states + outputs
214
+
215
+ return hidden_states, attn_weights, current_key_value
216
+
217
+
218
+ class CpmAntDenseGatedACT(nn.Module):
219
+ def __init__(self, config: CpmAntConfig):
220
+ super().__init__()
221
+ self.w_0 = nn.Linear(config.hidden_size, config.dim_ff, bias=False)
222
+ self.w_1 = nn.Linear(config.hidden_size, config.dim_ff, bias=False)
223
+ self.act = torch.nn.GELU()
224
+
225
+ def forward(self, hidden_states: torch.Tensor):
226
+ """Transform an input tensor from one feature space to another via a nonlinear operation
227
+
228
+ Args:
229
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
230
+ """
231
+ gate_score = self.act(self.w_0(hidden_states))
232
+ hidden_states = self.w_1(hidden_states)
233
+
234
+ hidden_states = gate_score * hidden_states
235
+ return hidden_states
236
+
237
+
238
+ class CpmAntFeedForward(nn.Module):
239
+ def __init__(self, config: CpmAntConfig):
240
+ super().__init__()
241
+ self.w_in = CpmAntDenseGatedACT(config)
242
+ if config.dropout_p is not None:
243
+ self.dropout = torch.nn.Dropout(config.dropout_p)
244
+ else:
245
+ self.dropout = None
246
+
247
+ self.w_out = nn.Linear(config.dim_ff, config.hidden_size, bias=False)
248
+
249
+ def forward(self, hidden_states: torch.Tensor):
250
+ """
251
+ Args:
252
+ hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
253
+ """
254
+ hidden_states = self.w_in(hidden_states)
255
+
256
+ if self.dropout is not None:
257
+ hidden_states = self.dropout(hidden_states)
258
+
259
+ hidden_states = self.w_out(hidden_states)
260
+
261
+ return hidden_states
262
+
263
+
264
+ class CpmAntFFNBlock(nn.Module):
265
+ def __init__(self, config: CpmAntConfig):
266
+ super().__init__()
267
+ self.layernorm_before_ffn = CpmAntLayerNorm(config)
268
+ self.ffn = CpmAntFeedForward(config)
269
+ if config.dropout_p:
270
+ self.dropout = torch.nn.Dropout(config.dropout_p)
271
+ else:
272
+ self.dropout = None
273
+
274
+ def forward(
275
+ self,
276
+ hidden_states: torch.Tensor,
277
+ ):
278
+ """
279
+ Args:
280
+ hidden_states (`torch.Tensor` of shape `(batch, len_seq, dim_model)`):
281
+ Hidden states before feed forward layer.
282
+ """
283
+ ln_outputs = self.layernorm_before_ffn(hidden_states)
284
+ outputs = self.ffn(ln_outputs)
285
+ if self.dropout is not None:
286
+ outputs = self.dropout(outputs)
287
+ hidden_states = hidden_states + outputs
288
+ return hidden_states
289
+
290
+
291
+ class CpmAntTransformerBlock(nn.Module):
292
+ def __init__(self, config: CpmAntConfig):
293
+ super().__init__()
294
+ self.self_att = CpmAntSelfAttentionBlock(config)
295
+ self.ffn = CpmAntFFNBlock(config)
296
+
297
+ def forward(
298
+ self,
299
+ hidden_states: torch.Tensor,
300
+ attention_mask: torch.Tensor,
301
+ position_bias: Optional[torch.Tensor] = None,
302
+ output_attentions: Optional[bool] = False,
303
+ past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
304
+ use_cache: Optional[bool] = None,
305
+ ):
306
+ """
307
+ Args:
308
+ hidden_states (`torch.Tensor`):
309
+ Input to the layer of shape `(batch, seq_len, dim_model)`
310
+ attention_mask (`torch.Tensor`):
311
+ Avoid invalid areas to participate in the calculation of shape `(batch, seq_len, seq_len)`
312
+ position_bias (`torch.Tensor`):
313
+ Provides position information to attention mechanism of shape `(num_heads, seq_len, seq_len)`
314
+ output_attentions (`bool`, *optional*):
315
+ Whether or not to return the attentions tensors of all attention layers.
316
+ past_key_values (`Tuple[torch.Tensor, torch.Tensor])`, *optional*):
317
+ Cached past key and value projection states
318
+ use_cache (`bool`, *optional*):
319
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
320
+ (see `past_key_values`).
321
+ """
322
+ hidden_states = self.self_att(
323
+ hidden_states,
324
+ attention_mask=attention_mask,
325
+ position_bias=position_bias,
326
+ output_attentions=output_attentions,
327
+ past_key_values=past_key_values,
328
+ use_cache=use_cache,
329
+ )
330
+
331
+ hidden_states, attn_weights, current_key_value = hidden_states
332
+
333
+ hidden_states = self.ffn(hidden_states)
334
+
335
+ return hidden_states, attn_weights, current_key_value
336
+
337
+
338
+ class CpmAntEncoder(nn.Module):
339
+ def __init__(self, config: CpmAntConfig):
340
+ super().__init__()
341
+ self.num_layers = config.num_hidden_layers
342
+ self.layers = nn.ModuleList([CpmAntTransformerBlock(config) for ith in range(self.num_layers)])
343
+
344
+ self.output_layernorm = CpmAntLayerNorm(config)
345
+
346
+ def forward(
347
+ self,
348
+ hidden_states: torch.Tensor,
349
+ attention_mask: torch.Tensor,
350
+ position_bias: torch.Tensor,
351
+ output_attentions: Optional[bool] = None,
352
+ output_hidden_states: Optional[bool] = None,
353
+ past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
354
+ use_cache: Optional[bool] = None,
355
+ ):
356
+ """
357
+ Args:
358
+ hidden_states (`torch.Tensor`):
359
+ Input to the layer of shape `(batch, seq_len, dim_model)`
360
+ attention_mask (`torch.Tensor`):
361
+ Avoid invalid areas to participate in the calculation of shape `(batch, seq_len, seq_len)`
362
+ position_bias (`torch.Tensor`):
363
+ Provides position information to attention mechanism of shape `(num_heads, seq_len, seq_len)`
364
+ output_attentions (`bool`, *optional*):
365
+ Whether or not to return the attentions tensors of all attention layers.
366
+ output_hidden_states (`bool`, *optional*):
367
+ Whether or not to return the hidden states of all layers.
368
+ past_key_values (`Tuple[torch.Tensor, torch.Tensor])`, *optional*):
369
+ Cached past key and value projection states
370
+ use_cache (`bool`, *optional*):
371
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
372
+ (see `past_key_values`).
373
+ """
374
+ all_hidden_states = () if output_hidden_states else None
375
+ all_self_attns = () if output_attentions else None
376
+ current_key_values = () if use_cache else None
377
+
378
+ for i, layer in enumerate(self.layers):
379
+ if output_hidden_states:
380
+ all_hidden_states += (hidden_states,)
381
+ layer_outputs = layer(
382
+ hidden_states,
383
+ attention_mask,
384
+ position_bias,
385
+ output_attentions=output_attentions,
386
+ past_key_values=past_key_values[i] if past_key_values else None,
387
+ use_cache=use_cache,
388
+ )
389
+ hidden_states, attn_weights, current_key_value = layer_outputs
390
+ if output_attentions:
391
+ all_self_attns += (attn_weights,)
392
+ if current_key_value is not None:
393
+ current_key_values = current_key_values + (current_key_value,)
394
+
395
+ hidden_states = self.output_layernorm(hidden_states)
396
+
397
+ if output_hidden_states:
398
+ all_hidden_states += (hidden_states,)
399
+
400
+ return hidden_states, current_key_values, all_hidden_states, all_self_attns
401
+
402
+
403
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->CPMAnt
404
+ class CpmAntIntermediate(nn.Module):
405
+ def __init__(self, config):
406
+ super().__init__()
407
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
408
+ if isinstance(config.hidden_act, str):
409
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
410
+ else:
411
+ self.intermediate_act_fn = config.hidden_act
412
+
413
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
414
+ hidden_states = self.dense(hidden_states)
415
+ hidden_states = self.intermediate_act_fn(hidden_states)
416
+ return hidden_states
417
+
418
+
419
+ class CpmAntSegmentPositionEmbedding(nn.Module):
420
+ def __init__(self, config: CpmAntConfig):
421
+ super().__init__()
422
+
423
+ self.num_heads = config.num_attention_heads
424
+ self.num_buckets = config.position_bias_num_buckets
425
+ self.max_distance = config.position_bias_max_distance
426
+ self.num_segments = config.segment_types
427
+
428
+ self.relative_attention_bias = nn.Parameter(
429
+ torch.empty(
430
+ config.segment_types * config.segment_types + config.position_bias_num_buckets,
431
+ config.num_attention_heads,
432
+ )
433
+ )
434
+
435
+ def forward(
436
+ self,
437
+ key_pos: torch.Tensor,
438
+ query_pos: torch.Tensor,
439
+ key_segment: torch.Tensor,
440
+ query_segment: torch.Tensor,
441
+ ):
442
+ with torch.no_grad():
443
+ batch = key_pos.size(0)
444
+ keylen = key_pos.size(1)
445
+ querylen = query_pos.size(1)
446
+
447
+ if key_pos.size(0) != query_pos.size(0):
448
+ raise AssertionError(
449
+ f"key_pos.size(0) should be equal to query_pos.size(0), but got {key_pos.size(0)} and {query_pos.size(0)}!"
450
+ )
451
+ if keylen != key_segment.size(1) or querylen != query_segment.size(1):
452
+ raise AssertionError(
453
+ f"keylen should be equal to key_segment.size(1), but got {keylen} and {key_segment.size(1)}!"
454
+ )
455
+ if querylen != query_segment.size(1):
456
+ raise AssertionError(
457
+ f"querylen should be equal to query_segment.size(1), but got {querylen} and {query_segment.szie(1)}!"
458
+ )
459
+
460
+ key_pos = key_pos.view(batch, -1, keylen)
461
+ query_pos = query_pos.view(batch, querylen, -1)
462
+ key_segment = key_segment.view(batch, -1, keylen)
463
+ query_segment = query_segment.view(batch, querylen, -1)
464
+
465
+ relative_position_bucket = self._segment_relative_position_bucket(query_segment, key_segment)
466
+ relative_position_bucket = relative_position_bucket + self.num_buckets
467
+
468
+ # (batch, len_q, len_k)
469
+ absolute_position_bucket = self._position_bucket(
470
+ torch.arange(keylen, dtype=torch.int32, device=relative_position_bucket.device)[None, :]
471
+ - torch.arange(querylen, dtype=torch.int32, device=relative_position_bucket.device)[:, None],
472
+ num_buckets=self.num_buckets,
473
+ max_distance=self.max_distance,
474
+ )
475
+ relative_position_bucket = torch.where(
476
+ (key_segment == query_segment),
477
+ absolute_position_bucket[None, :, :],
478
+ relative_position_bucket,
479
+ )
480
+
481
+ # (batch, len_q, len_k, num_heads)
482
+ embeds = F.embedding(relative_position_bucket, self.relative_attention_bias)
483
+ # (batch, num_heads, len_q, len_k)
484
+ embeds = embeds.permute(0, 3, 1, 2).contiguous()
485
+ return embeds
486
+
487
+ def _segment_relative_position_bucket(self, query_segment, key_segment):
488
+ return query_segment * self.num_segments + key_segment
489
+
490
+ def _position_bucket(self, relative_position, num_buckets=32, max_distance=128):
491
+ relative_buckets = 0
492
+ # always bidirectional in CPMAnt
493
+ num_buckets //= 2
494
+ relative_buckets = (relative_position > 0).to(torch.int32) * num_buckets
495
+ relative_position = torch.abs(relative_position)
496
+ max_exact = num_buckets // 2
497
+ is_small = relative_position < max_exact
498
+ relative_postion_if_large = max_exact + (
499
+ torch.log(relative_position.float() / max_exact)
500
+ / math.log(max_distance / max_exact)
501
+ * (num_buckets - max_exact)
502
+ ).to(torch.int32)
503
+ relative_postion_if_large = torch.min(
504
+ relative_postion_if_large,
505
+ torch.full_like(relative_postion_if_large, num_buckets - 1),
506
+ )
507
+ relative_buckets += torch.where(is_small, relative_position.to(torch.int32), relative_postion_if_large)
508
+ return relative_buckets
509
+
510
+
511
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->CPMAnt
512
+ class CpmAntOutput(nn.Module):
513
+ def __init__(self, config):
514
+ super().__init__()
515
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
516
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
517
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
518
+
519
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
520
+ hidden_states = self.dense(hidden_states)
521
+ hidden_states = self.dropout(hidden_states)
522
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
523
+ return hidden_states
524
+
525
+
526
+ class CpmAntPreTrainedModel(PreTrainedModel):
527
+ """
528
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
529
+ models.
530
+ """
531
+
532
+ config_class = CpmAntConfig
533
+ base_model_prefix = "cpmant"
534
+
535
+ def _init_weights(self, module):
536
+ """Initialize the weights"""
537
+ if isinstance(module, nn.Linear):
538
+ module.weight.data.normal_(mean=0.0, std=self.config.init_std)
539
+ if module.bias is not None:
540
+ module.bias.data.zero_()
541
+ elif isinstance(module, nn.Embedding):
542
+ module.weight.data.normal_(mean=0.0, std=self.config.init_std)
543
+ if module.padding_idx is not None:
544
+ module.weight.data[module.padding_idx].zero_()
545
+ elif isinstance(module, nn.LayerNorm):
546
+ module.bias.data.zero_()
547
+ module.weight.data.fill_(1.0)
548
+ elif isinstance(module, CpmAntLayerNorm):
549
+ module.weight.data.fill_(1.0)
550
+ elif isinstance(module, CpmAntSegmentPositionEmbedding):
551
+ module.relative_attention_bias.data.normal_(mean=0.0, std=self.config.init_std)
552
+
553
+
554
+ CPMANT_START_DOCSTRING = r"""
555
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
556
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
557
+ behavior.
558
+
559
+ Parameters
560
+ config ([`~CpmAntConfig`]): Model configuration class with all the parameters of the
561
+ Initializing with a config file does not load the weights associated with the model, only the
562
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
563
+ """
564
+
565
+ CPMANT_INPUTS_DOCSTRING = r"""
566
+ Args:
567
+ input_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):
568
+ Indices of input sequence tokens in the vocabulary.
569
+
570
+ Indices can be obtained using [`CPMAntTokenizer`]. See [`PreTrainedTokenizer.encode`] and
571
+ [`PreTrainedTokenizer.__call__`] for details.
572
+
573
+ [What are input IDs?](../glossary#input-ids)
574
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
575
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
576
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
577
+ use_cache (`bool`, *optional*):
578
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
579
+ `past_key_values`).
580
+ output_attentions (`bool`, *optional*):
581
+ Whether or not to return the attentions tensors of all attention layers.
582
+ output_hidden_states (`bool`, *optional*):
583
+ Whether or not to return the hidden states of all layers.
584
+ return_dict (`bool`, *optional*):
585
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
586
+ """
587
+
588
+
589
+ @add_start_docstrings(
590
+ "The bare CPMAnt Model outputting raw hidden-states without any specific head on top.",
591
+ CPMANT_START_DOCSTRING,
592
+ )
593
+ class CpmAntModel(CpmAntPreTrainedModel):
594
+ def __init__(self, config: CpmAntConfig):
595
+ super().__init__(config)
596
+ self.encoder = CpmAntEncoder(config)
597
+ self.segment_embedding = nn.Embedding(config.segment_types, config.hidden_size)
598
+ self.input_embedding = nn.Embedding(
599
+ config.vocab_size + config.prompt_types * config.prompt_length, config.hidden_size
600
+ )
601
+ self.position_bias = CpmAntSegmentPositionEmbedding(config)
602
+ self.prompt_length = config.prompt_length
603
+ self.vocab_size = config.vocab_size
604
+
605
+ self.post_init()
606
+
607
+ def get_input_embeddings(self):
608
+ return self.input_embedding
609
+
610
+ def set_input_embeddings(self, embeddings, **kwargs):
611
+ self.input_embedding = embeddings
612
+
613
+ def _prepare_attention_mask(self, input_ids, span, context, length):
614
+ batch = input_ids.size(0)
615
+ seqlen = input_ids.size(1)
616
+ device = input_ids.device
617
+ directional_mask_2d = torch.arange(seqlen, device=device) <= torch.arange(seqlen, device=device).view(-1, 1)
618
+ attention_mask = context[:, None, :] | (
619
+ context[:, :, None].logical_not() & directional_mask_2d.view(1, seqlen, seqlen)
620
+ )
621
+ attention_mask = attention_mask & (span[:, None, :] == span[:, :, None])
622
+ # mask for left padding
623
+ mask_1d = (
624
+ torch.tensor(list(range(seqlen - self.prompt_length))[::-1], device=device)[None, :].repeat(batch, 1)
625
+ < length[:, None]
626
+ )
627
+ mask_1d = torch.cat((torch.ones(batch, self.prompt_length, device=device).bool(), mask_1d), dim=1)
628
+ attention_mask = mask_1d.view(batch, seqlen, 1) & mask_1d.view(batch, 1, seqlen) & attention_mask
629
+ return attention_mask
630
+
631
+ @add_start_docstrings_to_model_forward(CPMANT_INPUTS_DOCSTRING)
632
+ @add_code_sample_docstrings(
633
+ checkpoint=_CHECKPOINT_FOR_DOC,
634
+ output_type=BaseModelOutputWithPast,
635
+ config_class=_CONFIG_FOR_DOC,
636
+ )
637
+ def forward(
638
+ self,
639
+ input_ids: Optional[torch.Tensor] = None,
640
+ output_attentions: Optional[bool] = None,
641
+ output_hidden_states: Optional[bool] = None,
642
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
643
+ use_cache: Optional[bool] = None,
644
+ return_dict: Optional[bool] = None,
645
+ **kwargs,
646
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPast]:
647
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
648
+ output_hidden_states = (
649
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
650
+ )
651
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
652
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
653
+
654
+ # add prompts ahead
655
+ if input_ids.dtype != torch.int32:
656
+ input_ids = input_ids.to(torch.int32)
657
+ dtype, device = input_ids.dtype, input_ids.device
658
+ segment = torch.where(input_ids != 0, 2, 0).to(dtype=dtype, device=device)
659
+ length = (segment != 0).sum(-1).to(dtype=dtype, device=device)
660
+ input_ids = torch.cat(
661
+ (
662
+ torch.arange(
663
+ self.prompt_length * 2 + self.vocab_size,
664
+ self.prompt_length * 3 + self.vocab_size,
665
+ dtype=dtype,
666
+ device=device,
667
+ ).repeat(input_ids.size(0), 1),
668
+ input_ids,
669
+ ),
670
+ dim=1,
671
+ )
672
+ batch, seq_length = input_ids.size()
673
+ segment = torch.cat((torch.zeros(batch, self.prompt_length, dtype=dtype, device=device), segment), dim=1)
674
+ context = torch.full((batch, seq_length), 1, dtype=dtype, device=device)
675
+ position = torch.arange(seq_length, dtype=dtype, device=device).repeat(batch, 1)
676
+ span = torch.full((batch, seq_length), 0, dtype=dtype, device=device)
677
+
678
+ if past_key_values is None:
679
+ past_length = 0
680
+ past_key_values = tuple([None] * self.encoder.num_layers)
681
+ input_ids = input_ids.contiguous()
682
+ hidden_states = self.input_embedding(input_ids)
683
+ segment_states = self.segment_embedding(segment)
684
+ hidden_states = hidden_states + segment_states
685
+ else:
686
+ past_length = past_key_values[0][0].size(-2)
687
+ segment_states = self.segment_embedding(segment)
688
+ hidden_states = self.input_embedding(input_ids) + segment_states[:, -1:, :]
689
+
690
+ attention_mask = self._prepare_attention_mask(input_ids, span, context, length)
691
+ position_bias = self.position_bias(position, position, segment, segment)
692
+
693
+ attention_mask = attention_mask[:, past_length:, :]
694
+ position_bias = position_bias[:, :, past_length:, :]
695
+ hidden_states = hidden_states[:, past_length:, :]
696
+
697
+ hidden_states, present_key_values, all_hidden_states, all_attentions = self.encoder(
698
+ hidden_states,
699
+ attention_mask,
700
+ position_bias,
701
+ output_attentions,
702
+ output_hidden_states,
703
+ past_key_values,
704
+ use_cache,
705
+ )
706
+
707
+ if past_length == 0:
708
+ hidden_states = hidden_states[:, self.prompt_length :, :]
709
+ # drop the prompt
710
+ if all_attentions is not None:
711
+ new_attentions = ()
712
+ for attention in all_attentions:
713
+ new_attentions += (attention[:, :, self.prompt_length :, self.prompt_length :],)
714
+ all_attentions = new_attentions
715
+ if all_hidden_states is not None:
716
+ new_hidden_states = ()
717
+ for hidden_state in all_hidden_states:
718
+ new_hidden_states += (hidden_state[:, self.prompt_length :, :],)
719
+ all_hidden_states = new_hidden_states
720
+
721
+ if not return_dict:
722
+ return tuple(
723
+ v for v in [hidden_states, present_key_values, all_hidden_states, all_attentions] if v is not None
724
+ )
725
+
726
+ return BaseModelOutputWithPast(
727
+ last_hidden_state=hidden_states,
728
+ past_key_values=present_key_values,
729
+ hidden_states=all_hidden_states,
730
+ attentions=all_attentions,
731
+ )
732
+
733
+
734
+ @add_start_docstrings(
735
+ """
736
+ The CPMAnt Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
737
+ """,
738
+ CPMANT_START_DOCSTRING,
739
+ )
740
+ class CpmAntForCausalLM(CpmAntPreTrainedModel, GenerationMixin):
741
+ _tied_weights_keys = ["lm_head.weight"]
742
+
743
+ def __init__(self, config: CpmAntConfig):
744
+ super().__init__(config)
745
+ self.cpmant = CpmAntModel(config)
746
+
747
+ # lm_head.weight is tied to cpmant.input_embedding.weight
748
+ self.lm_head = nn.Linear(
749
+ config.hidden_size, config.vocab_size + config.prompt_types * config.prompt_length, bias=False
750
+ )
751
+ self.post_init()
752
+
753
+ @add_start_docstrings_to_model_forward(CPMANT_INPUTS_DOCSTRING)
754
+ @add_code_sample_docstrings(
755
+ checkpoint=_CHECKPOINT_FOR_DOC,
756
+ output_type=CausalLMOutputWithPast,
757
+ config_class=_CONFIG_FOR_DOC,
758
+ )
759
+ def forward(
760
+ self,
761
+ input_ids: Optional[torch.Tensor] = None,
762
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
763
+ use_cache: Optional[bool] = None,
764
+ output_attentions: Optional[bool] = None,
765
+ output_hidden_states: Optional[bool] = None,
766
+ labels: Optional[torch.Tensor] = None,
767
+ return_dict: Optional[bool] = None,
768
+ attention_mask: Optional[torch.Tensor] = None, # dummy parameter for text-generation pipeline
769
+ **kwargs,
770
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
771
+ r"""
772
+ Args:
773
+ input_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):
774
+ Indices of input sequence tokens in the vocabulary.
775
+
776
+ Indices can be obtained using [`CPMAntTokenizer`]. See [`PreTrainedTokenizer.encode`] and
777
+ [`PreTrainedTokenizer.__call__`] for details.
778
+
779
+ [What are input IDs?](../glossary#input-ids)
780
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
781
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
782
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
783
+ use_cache (`bool`, *optional*):
784
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
785
+ (see `past_key_values`).
786
+ output_attentions (`bool`, *optional*):
787
+ Whether or not to return the attentions tensors of all attention layers.
788
+ output_hidden_states (`bool`, *optional*):
789
+ Whether or not to return the hidden states of all layers.
790
+ labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
791
+ Labels for computing the masked language modeling loss.
792
+ return_dict (`bool`, *optional*):
793
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
794
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
795
+ CPMAnt will process attention mask automatically, this parameter is a dummy parameter for
796
+ text-generation pipeline.
797
+
798
+ Example:
799
+
800
+ Text Generation with CpmAntForCausalLM.
801
+ ```python
802
+ >>> from transformers import CPMAntTokenizer, CpmAntForCausalLM
803
+
804
+ >>> texts = "今天天气不错,"
805
+ >>> model = CpmAntForCausalLM.from_pretrained("openbmb/cpm-ant-10b")
806
+ >>> tokenizer = CPMAntTokenizer.from_pretrained("openbmb/cpm-ant-10b")
807
+ >>> input_ids = tokenizer(texts, return_tensors="pt")
808
+ >>> outputs = model.generate(**input_ids)
809
+ >>> output_texts = tokenizer.batch_decode(outputs)
810
+ >>> print(output_texts)
811
+ ['今天天气不错,阳光明媚,我和妈妈一起去超市买东西。\n在超市里,我看到了一个很好玩的玩具,它的名字叫“机器人”。它有一个圆圆的脑袋,两只圆圆的眼睛,还有一个圆圆的']
812
+ ```
813
+ """
814
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
815
+
816
+ model_output = self.cpmant(
817
+ input_ids, output_attentions, output_hidden_states, past_key_values, use_cache, return_dict
818
+ )
819
+ hidden_states = model_output.last_hidden_state if return_dict else model_output[0]
820
+
821
+ logits = self.lm_head(hidden_states)
822
+
823
+ loss = None
824
+ if labels is not None:
825
+ loss_func = CrossEntropyLoss()
826
+ loss = loss_func(logits.view(-1, logits.size(-1)), labels.view(-1))
827
+
828
+ if not return_dict:
829
+ output = (logits,) + model_output[1:]
830
+ return ((loss,) + output) if loss is not None else output
831
+
832
+ return CausalLMOutputWithPast(
833
+ loss=loss,
834
+ logits=logits,
835
+ past_key_values=model_output.past_key_values,
836
+ hidden_states=model_output.hidden_states,
837
+ attentions=model_output.attentions,
838
+ )
839
+
840
+ def get_input_embeddings(self):
841
+ return self.cpmant.input_embedding
842
+
843
+ def set_input_embeddings(self, embeddings):
844
+ self.cpmant.input_embedding = embeddings
845
+
846
+ def get_output_embeddings(self):
847
+ return self.lm_head
848
+
849
+ def set_output_embeddings(self, new_embeddings):
850
+ self.lm_head = new_embeddings
851
+
852
+ def _reorder_cache(self, past_key_values, beam_idx):
853
+ past_key_values = [list(each) if each is not None else each for each in past_key_values]
854
+ for key_value_layer in past_key_values:
855
+ key_value_layer[0] = key_value_layer[0][beam_idx]
856
+ key_value_layer[1] = key_value_layer[1][beam_idx]
857
+ return past_key_values
858
+
859
+
860
+ __all__ = ["CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel"]
vllm/lib/python3.10/site-packages/transformers/models/cpmant/tokenization_cpmant.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The OpenBMB Team and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for CPMAnt."""
16
+
17
+ import collections
18
+ import os
19
+ from typing import List, Optional, Tuple
20
+
21
+ from transformers.utils import is_jieba_available, requires_backends
22
+
23
+
24
+ if is_jieba_available():
25
+ import jieba
26
+
27
+ from ...tokenization_utils import PreTrainedTokenizer
28
+ from ...utils import logging
29
+
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
34
+
35
+
36
+ def load_vocab(vocab_file):
37
+ """Loads a vocabulary file into a dictionary."""
38
+ vocab = collections.OrderedDict()
39
+ with open(vocab_file, "r", encoding="utf-8") as reader:
40
+ tokens = reader.readlines()
41
+ for index, token in enumerate(tokens):
42
+ token = token.rstrip("\n")
43
+ vocab[token] = index
44
+ return vocab
45
+
46
+
47
+ class WordpieceTokenizer:
48
+ def __init__(self, vocab, unk_token="<unk>", max_input_chars_per_word=200):
49
+ self.vocab = vocab
50
+ self.unk_token = unk_token
51
+ self.max_input_chars_per_word = max_input_chars_per_word
52
+
53
+ def tokenize(self, token):
54
+ chars = list(token)
55
+ if len(chars) > self.max_input_chars_per_word:
56
+ return [self.unk_token]
57
+
58
+ start = 0
59
+ sub_tokens = []
60
+ while start < len(chars):
61
+ end = len(chars)
62
+ cur_substr = None
63
+ while start < end:
64
+ substr = "".join(chars[start:end])
65
+ if substr in self.vocab:
66
+ cur_substr = substr
67
+ break
68
+ end -= 1
69
+ if cur_substr is None:
70
+ sub_tokens.append(self.unk_token)
71
+ start += 1
72
+ else:
73
+ sub_tokens.append(cur_substr)
74
+ start = end
75
+
76
+ return sub_tokens
77
+
78
+
79
+ class CpmAntTokenizer(PreTrainedTokenizer):
80
+ """
81
+ Construct a CPMAnt tokenizer. Based on byte-level Byte-Pair-Encoding.
82
+
83
+ Args:
84
+ vocab_file (`str`):
85
+ Path to the vocabulary file.
86
+ bod_token (`str`, *optional*, defaults to `"<d>"`):
87
+ The beginning of document token.
88
+ eod_token (`str`, *optional*, defaults to `"</d>"`):
89
+ The end of document token.
90
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
91
+ The beginning of sequence token.
92
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
93
+ The end of sequence token.
94
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
95
+ The token used for padding.
96
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
97
+ The unknown token.
98
+ line_token (`str`, *optional*, defaults to `"</n>"`):
99
+ The line token.
100
+ space_token (`str`, *optional*, defaults to `"</_>"`):
101
+ The space token.
102
+ """
103
+
104
+ vocab_files_names = VOCAB_FILES_NAMES
105
+ model_input_names = ["input_ids", "attention_mask"]
106
+ add_prefix_space = False
107
+
108
+ def __init__(
109
+ self,
110
+ vocab_file,
111
+ bod_token="<d>",
112
+ eod_token="</d>",
113
+ bos_token="<s>",
114
+ eos_token="</s>",
115
+ pad_token="<pad>",
116
+ unk_token="<unk>",
117
+ line_token="</n>",
118
+ space_token="</_>",
119
+ padding_side="left",
120
+ **kwargs,
121
+ ):
122
+ requires_backends(self, ["jieba"])
123
+ self.bod_token = bod_token
124
+ self.eod_token = eod_token
125
+ self.encoder = load_vocab(vocab_file)
126
+ self.encoder[" "] = self.encoder[space_token]
127
+ self.encoder["\n"] = self.encoder[line_token]
128
+
129
+ del self.encoder[space_token]
130
+ del self.encoder[line_token]
131
+
132
+ self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
133
+ self.decoder = {v: k for k, v in self.encoder.items()}
134
+
135
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.encoder, unk_token=unk_token)
136
+
137
+ super().__init__(
138
+ bod_token=bod_token,
139
+ eod_token=eod_token,
140
+ bos_token=bos_token,
141
+ eos_token=eos_token,
142
+ pad_token=pad_token,
143
+ unk_token=unk_token,
144
+ line_token=line_token,
145
+ space_token=space_token,
146
+ padding_side=padding_side,
147
+ **kwargs,
148
+ )
149
+
150
+ @property
151
+ def bod_token_id(self):
152
+ return self.encoder[self.bod_token]
153
+
154
+ @property
155
+ def eod_token_id(self):
156
+ return self.encoder[self.eod_token]
157
+
158
+ @property
159
+ def newline_id(self):
160
+ return self.encoder["\n"]
161
+
162
+ @property
163
+ def vocab_size(self) -> int:
164
+ return len(self.encoder)
165
+
166
+ def get_vocab(self):
167
+ return dict(self.encoder, **self.added_tokens_encoder)
168
+
169
+ def _tokenize(self, text):
170
+ """Tokenize a string."""
171
+ output_tokens = []
172
+ for x in jieba.cut(text, cut_all=False):
173
+ output_tokens.extend(self.wordpiece_tokenizer.tokenize(x))
174
+ return output_tokens
175
+
176
+ def _decode(self, token_ids, **kwargs):
177
+ """Decode ids into a string."""
178
+ token_ids = [i for i in token_ids if i >= 0]
179
+ token_ids = [
180
+ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
181
+ ]
182
+ return super()._decode(token_ids, **kwargs)
183
+
184
+ def check(self, token):
185
+ return token in self.encoder
186
+
187
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
188
+ return "".join(tokens)
189
+
190
+ def _convert_token_to_id(self, token):
191
+ """Converts a token (str) in an id using the vocab."""
192
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
193
+
194
+ def _convert_id_to_token(self, index):
195
+ """Converts an index (integer) in a token (str) using the vocab."""
196
+ return self.decoder.get(index, self.unk_token)
197
+
198
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
199
+ if os.path.isdir(save_directory):
200
+ vocab_file = os.path.join(
201
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
202
+ )
203
+ else:
204
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
205
+ index = 0
206
+ if " " in self.encoder:
207
+ self.encoder["</_>"] = self.encoder[" "]
208
+ del self.encoder[" "]
209
+ if "\n" in self.encoder:
210
+ self.encoder["</n>"] = self.encoder["\n"]
211
+ del self.encoder["\n"]
212
+ self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
213
+ with open(vocab_file, "w", encoding="utf-8") as writer:
214
+ for token, token_index in self.encoder.items():
215
+ if index != token_index:
216
+ logger.warning(
217
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
218
+ " Please check that the vocabulary is not corrupted!"
219
+ )
220
+ index = token_index
221
+ writer.write(token + "\n")
222
+ index += 1
223
+ return (vocab_file,)
224
+
225
+ def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: List[int] = None) -> List[int]:
226
+ """
227
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
228
+ adding special tokens. A CPMAnt sequence has the following format:
229
+
230
+ - single sequence: `[BOS] Sequence`.
231
+
232
+ Args:
233
+ token_ids_0 (`List[int]`): The first tokenized sequence that special tokens will be added.
234
+ token_ids_1 (`List[int]`): The optional second tokenized sequence that special tokens will be added.
235
+
236
+ Returns:
237
+ `List[int]`: The model input with special tokens.
238
+ """
239
+ if token_ids_1 is None:
240
+ return [self.bos_token_id] + token_ids_0
241
+ return [self.bos_token_id] + token_ids_0 + [self.bos_token_id] + token_ids_1
242
+
243
+ def get_special_tokens_mask(
244
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
245
+ ) -> List[int]:
246
+ """
247
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
248
+ special tokens using the tokenizer `prepare_for_model` method.
249
+
250
+ Args:
251
+ token_ids_0 (`List[int]`): List of IDs.
252
+ token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs.
253
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
254
+ Whether or not the token list is already formatted with special tokens for the model.
255
+
256
+ Returns:
257
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
258
+ """
259
+
260
+ if already_has_special_tokens:
261
+ return super().get_special_tokens_mask(
262
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
263
+ )
264
+
265
+ if token_ids_1 is not None:
266
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
267
+ return [1] + ([0] * len(token_ids_0))
268
+
269
+
270
+ __all__ = ["CpmAntTokenizer"]
vllm/lib/python3.10/site-packages/transformers/models/deformable_detr/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import TYPE_CHECKING
17
+
18
+ from ...utils import _LazyModule
19
+ from ...utils.import_utils import define_import_structure
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from .configuration_deformable_detr import *
24
+ from .feature_extraction_deformable_detr import *
25
+ from .image_processing_deformable_detr import *
26
+ from .image_processing_deformable_detr_fast import *
27
+ from .modeling_deformable_detr import *
28
+ else:
29
+ import sys
30
+
31
+ _file = globals()["__file__"]
32
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (702 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-310.pyc ADDED
Binary file (12 kB). View file