-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_goal_function_core.py
More file actions
602 lines (475 loc) · 21.2 KB
/
test_goal_function_core.py
File metadata and controls
602 lines (475 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
"""
Comprehensive tests for MultilabelClassificationGoalFunction.
This test suite covers:
- Output processing and validation
- Score calculation logic
- Goal completion detection
- Edge cases and error handling
- Result formatting
"""
import pytest
import numpy as np
import torch
from unittest.mock import Mock, MagicMock
from textattack_multilabel.goal_function import (
MultilabelClassificationGoalFunction,
MultilabelClassificationGoalFunctionResult,
)
class TestMultilabelClassificationGoalFunctionInit:
"""Test initialization and configuration."""
def test_init_with_defaults(self):
"""Test initialization with default parameters."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(mock_model)
assert goal_func.model == mock_model
assert goal_func.labels_to_maximize == [0]
assert goal_func.labels_to_minimize == []
assert goal_func.maximize_target_score == 0.5
assert goal_func.minimize_target_score == 0.5
def test_init_with_single_int_labels(self):
"""Test initialization with integer labels (converted to list)."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
labels_to_maximize=2,
labels_to_minimize=3
)
assert goal_func.labels_to_maximize == [2]
assert goal_func.labels_to_minimize == [3]
def test_init_with_list_labels(self):
"""Test initialization with list of labels."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
labels_to_maximize=[0, 1, 2],
labels_to_minimize=[3, 4, 5]
)
assert goal_func.labels_to_maximize == [0, 1, 2]
assert goal_func.labels_to_minimize == [3, 4, 5]
def test_init_with_custom_thresholds(self):
"""Test initialization with custom target scores."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
maximize_target_score=0.8,
minimize_target_score=0.2
)
assert goal_func.maximize_target_score == 0.8
assert goal_func.minimize_target_score == 0.2
def test_init_with_none_minimize(self):
"""Test initialization with None for minimize labels."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=None
)
assert goal_func.labels_to_maximize == [0, 1]
assert goal_func.labels_to_minimize == []
def test_init_validates_labels_provided(self):
"""Test that initialization fails when neither maximize nor minimize labels provided."""
mock_model = Mock()
with pytest.raises(AssertionError):
MultilabelClassificationGoalFunction(
mock_model,
labels_to_maximize=[],
labels_to_minimize=[]
)
class TestProcessModelOutputs:
"""Test _process_model_outputs method."""
def setup_method(self):
"""Setup test fixtures."""
self.mock_model = Mock()
self.goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=[2, 3]
)
def test_process_tensor_2d(self):
"""Test processing 2D tensor (batch of predictions)."""
outputs = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6]])
result = self.goal_func._process_model_outputs(outputs=outputs)
assert isinstance(result, torch.Tensor)
assert result.shape == (1, 6)
assert torch.allclose(result, outputs)
def test_process_tensor_1d(self):
"""Test processing 1D tensor (single prediction) - should unsqueeze."""
outputs = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
result = self.goal_func._process_model_outputs(outputs=outputs)
assert isinstance(result, torch.Tensor)
assert result.shape == (1, 6)
assert torch.allclose(result, outputs.unsqueeze(0))
def test_process_numpy_array(self):
"""Test processing numpy array (converted to tensor)."""
outputs = np.array([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6]])
result = self.goal_func._process_model_outputs(outputs=outputs)
assert isinstance(result, torch.Tensor)
assert result.shape == (1, 6)
assert torch.allclose(result, torch.tensor(outputs, dtype=torch.float))
def test_process_list(self):
"""Test processing list (converted to tensor)."""
outputs = [[0.1, 0.2, 0.3, 0.4, 0.5, 0.6]]
result = self.goal_func._process_model_outputs(outputs=outputs)
assert isinstance(result, torch.Tensor)
assert result.shape == (1, 6)
def test_process_invalid_type_raises_error(self):
"""Test that invalid types raise TypeError."""
with pytest.raises(TypeError, match="Must have"):
self.goal_func._process_model_outputs(outputs="invalid")
with pytest.raises(TypeError, match="Must have"):
self.goal_func._process_model_outputs(outputs=123)
def test_process_3d_tensor_raises_error(self):
"""Test that 3D tensors raise ValueError."""
outputs = torch.randn(2, 3, 4)
with pytest.raises(ValueError, match="must be 1D or 2D"):
self.goal_func._process_model_outputs(outputs=outputs)
def test_process_wrong_batch_size_raises_error(self):
"""Test that wrong batch size raises ValueError."""
outputs = torch.randn(3, 6) # batch_size=3, but we expect 1
with pytest.raises(ValueError, match=r"Model return score of shape .* for 1 inputs\."):
self.goal_func._process_model_outputs(outputs=outputs)
def test_process_values_out_of_range_applies_sigmoid(self):
"""Test that values outside [0,1] trigger sigmoid application."""
# Raw logits (outside [0,1] range)
outputs = torch.tensor([[2.5, -1.3, 0.8, -0.5, 1.2, 0.3]])
result = self.goal_func._process_model_outputs(outputs=outputs)
# Result should be sigmoid of input
expected = torch.sigmoid(outputs)
assert torch.allclose(result, expected, atol=1e-5)
def test_process_values_in_range_no_sigmoid(self):
"""Test that values in [0,1] are not modified."""
outputs = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5, 0.6]])
result = self.goal_func._process_model_outputs(outputs=outputs)
# Should be unchanged (no sigmoid)
assert torch.allclose(result, outputs)
def test_process_edge_case_zeros(self):
"""Test processing all-zero outputs."""
outputs = torch.zeros(1, 6)
result = self.goal_func._process_model_outputs(outputs=outputs)
assert torch.allclose(result, outputs)
def test_process_edge_case_ones(self):
"""Test processing all-one outputs."""
outputs = torch.ones(1, 6)
result = self.goal_func._process_model_outputs(outputs=outputs)
assert torch.allclose(result, outputs)
class TestGetScore:
"""Test _get_score method."""
def setup_method(self):
"""Setup test fixtures."""
self.mock_model = Mock()
def test_score_maximize_only(self):
"""Test score calculation with only maximize labels."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1, 2],
labels_to_minimize=[]
)
model_output = torch.tensor([0.3, 0.5, 0.7, 0.1, 0.2, 0.4])
score = goal_func._get_score(model_output, "sample text")
# Score = sum of labels_to_maximize = 0.3 + 0.5 + 0.7 = 1.5
expected_score = 0.3 + 0.5 + 0.7
assert abs(score - expected_score) < 1e-5
def test_score_minimize_only(self):
"""Test score calculation with only minimize labels."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[],
labels_to_minimize=[3, 4, 5]
)
model_output = torch.tensor([0.3, 0.5, 0.7, 0.2, 0.4, 0.6])
score = goal_func._get_score(model_output, "sample text")
# Score = (1 - sum of labels_to_minimize) = 1 - (0.2 + 0.4 + 0.6) = 1 - 1.2 = -0.2
expected_score = 1 - (0.2 + 0.4 + 0.6)
assert abs(score - expected_score) < 1e-5
def test_score_both_maximize_and_minimize(self):
"""Test score calculation with both maximize and minimize labels."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=[3, 4]
)
model_output = torch.tensor([0.8, 0.7, 0.5, 0.1, 0.2, 0.3])
score = goal_func._get_score(model_output, "sample text")
# Score = sum(maximize) + (1 - sum(minimize))
# = (0.8 + 0.7) + (1 - (0.1 + 0.2))
# = 1.5 + 0.7 = 2.2
expected_score = (0.8 + 0.7) + (1 - (0.1 + 0.2))
assert abs(score - expected_score) < 1e-5
def test_score_single_label_maximize(self):
"""Test score with single maximize label."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[2],
labels_to_minimize=[]
)
model_output = torch.tensor([0.1, 0.2, 0.9, 0.1, 0.1, 0.1])
score = goal_func._get_score(model_output, "sample text")
assert abs(score - 0.9) < 1e-5
def test_score_single_label_minimize(self):
"""Test score with single minimize label."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[],
labels_to_minimize=[2]
)
model_output = torch.tensor([0.1, 0.2, 0.3, 0.1, 0.1, 0.1])
score = goal_func._get_score(model_output, "sample text")
# Score = 1 - 0.3 = 0.7
assert abs(score - 0.7) < 1e-5
def test_score_all_labels_maximize(self):
"""Test maximizing all labels."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1, 2, 3, 4, 5],
labels_to_minimize=[]
)
model_output = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
score = goal_func._get_score(model_output, "sample text")
expected_score = sum([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
assert abs(score - expected_score) < 1e-5
def test_score_all_labels_minimize(self):
"""Test minimizing all labels."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[],
labels_to_minimize=[0, 1, 2, 3, 4, 5]
)
model_output = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
score = goal_func._get_score(model_output, "sample text")
expected_score = 1 - sum([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
assert abs(score - expected_score) < 1e-5
class TestIsGoalComplete:
"""Test _is_goal_complete method."""
def setup_method(self):
"""Setup test fixtures."""
self.mock_model = Mock()
def test_goal_complete_maximize_all_above_threshold(self):
"""Test goal completion when all maximize labels exceed threshold."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1, 2],
labels_to_minimize=[],
maximize_target_score=0.7
)
# All maximize labels > 0.7
model_output = torch.tensor([0.8, 0.9, 0.75, 0.1, 0.2, 0.3])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is True
def test_goal_incomplete_maximize_one_below_threshold(self):
"""Test goal incomplete when one maximize label below threshold."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1, 2],
labels_to_minimize=[],
maximize_target_score=0.7
)
# One maximize label (0.6) < 0.7
model_output = torch.tensor([0.8, 0.9, 0.6, 0.1, 0.2, 0.3])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is False
def test_goal_complete_minimize_all_below_threshold(self):
"""Test goal completion when all minimize labels below threshold."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[],
labels_to_minimize=[3, 4, 5],
minimize_target_score=0.3
)
# All minimize labels < 0.3
model_output = torch.tensor([0.8, 0.9, 0.75, 0.1, 0.2, 0.25])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is True
def test_goal_incomplete_minimize_one_above_threshold(self):
"""Test goal incomplete when one minimize label above threshold."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[],
labels_to_minimize=[3, 4, 5],
minimize_target_score=0.3
)
# One minimize label (0.4) > 0.3
model_output = torch.tensor([0.8, 0.9, 0.75, 0.1, 0.2, 0.4])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is False
def test_goal_complete_both_maximize_and_minimize(self):
"""Test goal completion with both maximize and minimize labels."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=[4, 5],
maximize_target_score=0.8,
minimize_target_score=0.2
)
# Maximize labels > 0.8 AND minimize labels < 0.2
model_output = torch.tensor([0.85, 0.9, 0.5, 0.5, 0.15, 0.1])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is True
def test_goal_incomplete_maximize_success_minimize_fail(self):
"""Test goal incomplete when maximize succeeds but minimize fails."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=[4, 5],
maximize_target_score=0.8,
minimize_target_score=0.2
)
# Maximize OK (> 0.8), but minimize fails (0.3 > 0.2)
model_output = torch.tensor([0.85, 0.9, 0.5, 0.5, 0.15, 0.3])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is False
def test_goal_incomplete_maximize_fail_minimize_success(self):
"""Test goal incomplete when maximize fails but minimize succeeds."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=[4, 5],
maximize_target_score=0.8,
minimize_target_score=0.2
)
# Maximize fails (0.75 < 0.8), but minimize OK (< 0.2)
model_output = torch.tensor([0.75, 0.9, 0.5, 0.5, 0.15, 0.1])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is False
def test_goal_complete_empty_maximize_labels(self):
"""Test goal complete when no maximize labels (always True)."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[],
labels_to_minimize=[4, 5],
minimize_target_score=0.2
)
# No maximize labels, so max_complete = True
# Minimize labels < 0.2, so min_complete = True
model_output = torch.tensor([0.5, 0.5, 0.5, 0.5, 0.1, 0.15])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is True
def test_goal_complete_empty_minimize_labels(self):
"""Test goal complete when no minimize labels (always True)."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=[],
maximize_target_score=0.8
)
# Maximize labels > 0.8, so max_complete = True
# No minimize labels, so min_complete = True
model_output = torch.tensor([0.85, 0.9, 0.5, 0.5, 0.5, 0.5])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is True
def test_goal_edge_case_exactly_at_threshold(self):
"""Test goal completion when values exactly at threshold."""
goal_func = MultilabelClassificationGoalFunction(
self.mock_model,
labels_to_maximize=[0],
labels_to_minimize=[1],
maximize_target_score=0.8,
minimize_target_score=0.2
)
# Exactly at threshold - should NOT complete (needs to EXCEED for maximize)
model_output = torch.tensor([0.8, 0.2, 0.5, 0.5, 0.5, 0.5])
result = goal_func._is_goal_complete(model_output, "sample text")
assert result is False # 0.8 is NOT > 0.8, and 0.2 is NOT < 0.2
class TestGoalFunctionResult:
"""Test MultilabelClassificationGoalFunctionResult."""
def test_result_type_returned(self):
"""Test that correct result type is returned."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(mock_model)
result_type = goal_func._goal_function_result_type()
assert result_type == MultilabelClassificationGoalFunctionResult
def test_result_get_text_color_input(self):
"""Test get_text_color_input returns 'blue'."""
result = MultilabelClassificationGoalFunctionResult(
attacked_text=Mock(),
raw_output=None,
output=0.5,
goal_status=Mock(),
score=1.0,
num_queries=1,
ground_truth_output=0.0
)
assert result.get_text_color_input() == "blue"
def test_result_get_text_color_perturbed(self):
"""Test get_text_color_perturbed returns 'red'."""
result = MultilabelClassificationGoalFunctionResult(
attacked_text=Mock(),
raw_output=None,
output=0.5,
goal_status=Mock(),
score=1.0,
num_queries=1,
ground_truth_output=0.0
)
assert result.get_text_color_perturbed() == "red"
def test_result_get_colored_output(self):
"""Test get_colored_output returns integer."""
result = MultilabelClassificationGoalFunctionResult(
attacked_text=Mock(),
raw_output=None,
output=5.7,
goal_status=Mock(),
score=1.0,
num_queries=1,
ground_truth_output=0.0
)
# Should return int(output)
assert result.get_colored_output() == 5
class TestEdgeCasesAndValidation:
"""Test edge cases and validation scenarios."""
def test_large_number_of_labels(self):
"""Test with many labels."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
labels_to_maximize=list(range(50)),
labels_to_minimize=list(range(50, 100))
)
assert len(goal_func.labels_to_maximize) == 50
assert len(goal_func.labels_to_minimize) == 50
def test_very_high_threshold(self):
"""Test with very high target score."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
maximize_target_score=0.99
)
model_output = torch.tensor([0.98, 0.5, 0.5, 0.5, 0.5, 0.5])
result = goal_func._is_goal_complete(model_output, "text")
assert result is False # 0.98 not > 0.99
def test_very_low_threshold(self):
"""Test with very low target score."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
labels_to_minimize=[0],
minimize_target_score=0.01
)
model_output = torch.tensor([0.02, 0.5, 0.5, 0.5, 0.5, 0.5])
result = goal_func._is_goal_complete(model_output, "text")
assert result is False # 0.02 not < 0.01
def test_score_with_zero_probabilities(self):
"""Test score calculation with zero probabilities."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=[2, 3]
)
model_output = torch.tensor([0.0, 0.0, 0.0, 0.0, 0.5, 0.5])
score = goal_func._get_score(model_output, "text")
# (0.0 + 0.0) + (1 - (0.0 + 0.0)) = 0 + 1 = 1.0
assert abs(score - 1.0) < 1e-5
def test_score_with_one_probabilities(self):
"""Test score calculation with probability 1.0."""
mock_model = Mock()
goal_func = MultilabelClassificationGoalFunction(
mock_model,
labels_to_maximize=[0, 1],
labels_to_minimize=[2, 3]
)
model_output = torch.tensor([1.0, 1.0, 0.0, 0.0, 0.5, 0.5])
score = goal_func._get_score(model_output, "text")
# (1.0 + 1.0) + (1 - (0.0 + 0.0)) = 2.0 + 1.0 = 3.0
assert abs(score - 3.0) < 1e-5
if __name__ == "__main__":
pytest.main([__file__, "-v"])