File size: 5,257 Bytes
9079f0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch

from torch import nn

from transformers import PreTrainedModel
from transformers.modeling_outputs import SequenceClassifierOutput

from .configuration_yield import YieldConfig
from .yield_transformer import YieldTransformer


class YieldForSequenceClassification(PreTrainedModel):

    config_class = YieldConfig
    base_model_prefix = "yield_model"

    def __init__(self, config: YieldConfig):
        super().__init__(config)

        self.yield_model = YieldTransformer(
            w_dim=config.W,
            soil_dim=config.S,
            d_model=config.d_model,
            nhead=config.nhead,
            num_layers=config.num_layers,
            dim_ff=config.dim_ff,
            dropout=config.dropout,
            use_crop=config.use_crop,
            crop_emb_dim=config.crop_emb_dim,
            max_weeks=max(52, config.K),
            pool=config.pool,
        )

        self.post_init()

    def forward(
        self,
        weather,
        soil,
        crop_id,
        horizon_idx=None,
        labels=None,
        **kwargs,
    ):

        # ==================================================
        # Shape checks
        # ==================================================

        if weather.ndim != 3:
            raise ValueError(
                f"weather must have shape [B,K,W], "
                f"received {tuple(weather.shape)}"
            )

        if soil.ndim != 2:
            raise ValueError(
                f"soil must have shape [B,S], "
                f"received {tuple(soil.shape)}"
            )

        # ==================================================
        # Training normalization statistics
        # ==================================================

        w_mean = torch.tensor(
            self.config.w_mean,
            device=weather.device,
            dtype=weather.dtype,
        )

        w_std = torch.tensor(
            self.config.w_std,
            device=weather.device,
            dtype=weather.dtype,
        )

        s_mean = torch.tensor(
            self.config.s_mean,
            device=soil.device,
            dtype=soil.dtype,
        )

        s_std = torch.tensor(
            self.config.s_std,
            device=soil.device,
            dtype=soil.dtype,
        )

        # NaN -> training mean
        weather = torch.where(
            torch.isnan(weather),
            w_mean.view(1, 1, -1),
            weather,
        )

        soil = torch.where(
            torch.isnan(soil),
            s_mean.view(1, -1),
            soil,
        )

        # normalize
        weather = (
            weather - w_mean.view(1, 1, -1)
        ) / w_std.view(1, 1, -1)

        soil = (
            soil - s_mean.view(1, -1)
        ) / s_std.view(1, -1)

        # ==================================================
        # Cutoff
        # ==================================================

        if horizon_idx is None:
            horizon_idx = torch.full(
                (weather.shape[0],),
                weather.shape[1],
                dtype=torch.long,
                device=weather.device,
            )

        if not torch.is_tensor(horizon_idx):
            horizon_idx = torch.tensor(
                horizon_idx,
                dtype=torch.long,
                device=weather.device,
            )

        horizon_idx = horizon_idx.to(
            weather.device
        ).long()

        if horizon_idx.ndim == 0:
            horizon_idx = horizon_idx.unsqueeze(0)

        # FlexServe requests are normally one sample.
        # Ensure one common temporal length for a batch.
        unique_cutoffs = torch.unique(
            horizon_idx
        )

        if len(unique_cutoffs) != 1:
            raise ValueError(
                "All samples in one batch must use the same cutoff."
            )

        t_eff = int(
            unique_cutoffs[0].item()
        )

        weather = weather[
            :,
            :t_eff,
            :
        ]

        # ==================================================
        # Existing trained model
        # ==================================================

        logits_norm = self.yield_model(
            weather,
            soil,
            crop_id,
            horizon_idx=horizon_idx,
            causal=True,
            return_sequence=False,
        )

        # Restore yield to bu/acre.
        y_mean = torch.tensor(
            self.config.y_mean,
            device=logits_norm.device,
            dtype=logits_norm.dtype,
        )

        y_std = torch.tensor(
            self.config.y_std,
            device=logits_norm.device,
            dtype=logits_norm.dtype,
        )

        predicted_yield = (
            logits_norm * y_std
            + y_mean
        )

        # TextClassificationPipeline expects [B, num_labels].
        logits = predicted_yield.unsqueeze(-1)

        loss = None

        if labels is not None:

            labels = labels.to(
                logits.dtype
            ).view(-1)

            loss = nn.functional.mse_loss(
                predicted_yield,
                labels,
            )

        return SequenceClassifierOutput(
            loss=loss,
            logits=logits,
        )