File size: 2,362 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""BikeBench notebook 3, with the public task evaluator/catalog adapter.

See ../PORT.md for pinned sources and the LibMoon API compatibility issue.
"""
import os
import sys
import time

START = time.monotonic()
sys.path.insert(0, os.environ["CORE_DIR"])
import numpy as np
import torch
from interface.api import read_instance, read_catalog, evaluate_tensor, write_output, OBJECTIVE_MASK
from preferences import uniform_pref
from scalarization import tche

torch.set_num_threads(2)
torch.set_num_interop_threads(1)


def solve(data, output):
    d, context = read_instance(data)
    train = torch.from_numpy(read_catalog())
    mask = torch.tensor(OBJECTIVE_MASK)
    lower, upper = train.amin(0), train.amax(0)
    with torch.no_grad():
        scores = evaluate_tensor(train, context)
        obj_std = scores[:, mask].std(dim=0).clamp_min(1e-6)
        penalty_scale = obj_std.mean()
        fpen = scores[:, mask] / obj_std + 1e3 * scores[:, ~mask].clamp_min(0).sum(1, keepdim=True) / penalty_scale
        prefs = torch.tensor(uniform_pref(2, int(mask.sum()), clip_eps=1e-2), dtype=torch.float32)
        ideal = fpen.min(0, keepdim=True).values
        values = ((fpen.unsqueeze(1) - ideal).abs() * prefs.unsqueeze(0)).max(2).values
        x = train[values.argmin(0)].clone().requires_grad_(True)

    optimizer = torch.optim.SGD([x], lr=1.0)
    completed = 0
    for _ in range(126):
        if time.monotonic() - START > float(os.environ.get("TASK_BUDGET_SEC", 60)) - 5:
            break
        scores = evaluate_tensor(x, context)
        f = scores[:, mask] / obj_std + 1e3 * scores[:, ~mask].clamp_min(0).sum(1, keepdim=True) / penalty_scale
        loss = tche(f, prefs).sum()
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        with torch.no_grad():
            x.clamp_(lower + 1e-5, upper - 1e-5)
        completed += 1

    result = x.detach()[torch.isfinite(x).all(1)]
    if result.numel() == 0:
        raise RuntimeError("All solutions contained NaNs/Infs; nothing to return.")
    n = int(d["output_rows"])
    if len(result) < n:
        result = result.repeat(((n + len(result) - 1) // len(result), 1))
    write_output(output, result[:n].numpy())
    print(f"steps={completed}; elapsed={time.monotonic()-START:.3f}", file=sys.stderr)


if __name__ == "__main__":
    solve(sys.argv[1], sys.argv[2])