Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
124 lines
4.7 KiB
Python
124 lines
4.7 KiB
Python
import math
|
|
import sys
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "simulation/semantic-learning"))
|
|
import weighted_paint_loss as subject
|
|
|
|
try:
|
|
import torch
|
|
from torch.nn import functional as functional
|
|
except ImportError:
|
|
torch = None
|
|
|
|
|
|
@unittest.skipIf(torch is None, "Torch training runtime required; run on pinned Worker image")
|
|
class WeightedPaintLossTests(unittest.TestCase):
|
|
def example(self):
|
|
x = torch.tensor(
|
|
[[[[1.0, -2.0, 8.0], [0.3, -0.4, 1.0]], [[-0.5, 3.0, -9.0], [1.0, 0.8, -0.1]]]],
|
|
dtype=torch.float64,
|
|
)
|
|
y = torch.tensor([[[0, 1, 255], [1, 0, 255]]])
|
|
return x, y
|
|
|
|
def test_weighted_mean_formula(self):
|
|
x, y = self.example()
|
|
weights = [1.0, 8.0]
|
|
expected = (
|
|
sum(
|
|
-x.log_softmax(1)[0, int(y[0, a, b]), a, b] * weights[int(y[0, a, b])]
|
|
for a, b in [(0, 0), (0, 1), (1, 0), (1, 1)]
|
|
)
|
|
/ 18
|
|
)
|
|
self.assertTrue(
|
|
torch.allclose(subject.weighted_paint_cross_entropy(x, y, weights), expected)
|
|
)
|
|
|
|
def test_unknown_has_zero_gradient(self):
|
|
x, y = self.example()
|
|
x.requires_grad_()
|
|
subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0]).backward()
|
|
self.assertEqual(torch.count_nonzero(x.grad.permute(0, 2, 3, 1)[y == 255]), 0)
|
|
self.assertGreater(torch.count_nonzero(x.grad.permute(0, 2, 3, 1)[y != 255]), 0)
|
|
|
|
def test_ignore_padding_invariance(self):
|
|
x, y = self.example()
|
|
a = subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0])
|
|
b = subject.weighted_paint_cross_entropy(
|
|
functional.pad(x, (0, 2), value=50), functional.pad(y, (0, 2), value=255), [1.0, 8.0]
|
|
)
|
|
self.assertTrue(torch.allclose(a, b))
|
|
|
|
def test_uniform_weights_reproduce_original(self):
|
|
x, y = self.example()
|
|
self.assertTrue(
|
|
torch.allclose(
|
|
subject.weighted_paint_cross_entropy(x, y, [1.0, 1.0]),
|
|
functional.cross_entropy(x, y, ignore_index=255),
|
|
)
|
|
)
|
|
|
|
def test_bg_only_not_weakened_and_correct_gradient(self):
|
|
y = torch.zeros((1, 2, 2), dtype=torch.long)
|
|
x = torch.zeros((1, 2, 2, 2), dtype=torch.float64, requires_grad=True)
|
|
loss = subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0])
|
|
self.assertTrue(torch.allclose(loss, functional.cross_entropy(x, y)))
|
|
loss.backward()
|
|
self.assertTrue(bool((x.grad[:, 1] > 0).all()))
|
|
z = x.detach().clone()
|
|
z[:, 1] += 2
|
|
self.assertGreater(subject.weighted_paint_cross_entropy(z, y, [1.0, 8.0]), loss)
|
|
|
|
def test_common_weight_scale_invariant(self):
|
|
x, y = self.example()
|
|
self.assertTrue(
|
|
torch.allclose(
|
|
subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0]),
|
|
subject.weighted_paint_cross_entropy(x, y, [2.0, 16.0]),
|
|
)
|
|
)
|
|
|
|
def test_permutations_preserve_loss(self):
|
|
x, y = self.example()
|
|
expected = subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0])
|
|
for k in range(4):
|
|
for flip in [False, True]:
|
|
a, b = x.rot90(k, (2, 3)), y.rot90(k, (1, 2))
|
|
if flip:
|
|
a, b = a.flip(-1), b.flip(-1)
|
|
self.assertTrue(
|
|
torch.allclose(expected, subject.weighted_paint_cross_entropy(a, b, [1.0, 8.0]))
|
|
)
|
|
|
|
def test_all_unknown_rejected(self):
|
|
x, y = self.example()
|
|
with self.assertRaises(ValueError):
|
|
subject.weighted_paint_cross_entropy(x, torch.full_like(y, 255), [1.0, 8.0])
|
|
|
|
def test_invalid_weights_rejected(self):
|
|
x, y = self.example()
|
|
for w in [[1.0], [0.0, 1.0], [1.0, -2.0], [math.inf, 1.0], [math.nan, 1.0], [1.0, 1e100]]:
|
|
with self.subTest(weights=w), self.assertRaises(ValueError):
|
|
subject.weighted_paint_cross_entropy(x.float(), y, w)
|
|
|
|
def test_invalid_labels_and_shape_rejected(self):
|
|
x, y = self.example()
|
|
for target in [y.float(), y[..., :2], torch.full_like(y, 2)]:
|
|
with self.assertRaises(ValueError):
|
|
subject.weighted_paint_cross_entropy(x, target, [1.0, 8.0])
|
|
with self.assertRaises(ValueError):
|
|
subject.weighted_paint_cross_entropy(x[:, :1], y, [1.0, 8.0])
|
|
|
|
def test_rare_paint_error_has_larger_gradient(self):
|
|
x = torch.zeros((1, 2, 1, 2), dtype=torch.float64, requires_grad=True)
|
|
y = torch.tensor([[[0, 1]]])
|
|
subject.weighted_paint_cross_entropy(x, y, [1.0, 8.0]).backward()
|
|
self.assertAlmostEqual(float(x.grad[0, 1, 0, 1].abs() / x.grad[0, 1, 0, 0].abs()), 8.0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|