-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_modeling.py
57 lines (43 loc) · 1.79 KB
/
context_modeling.py
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
import torch
from torch.autograd.grad_mode import no_grad
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class ContextModeler(nn.Module):
def __init__(self):
super(ContextModeler, self).__init__()
def forward(self, prev_sysout, candidate_pair, user_utt):
# cs: tensor -> candidate slot embedding
# cv: tensor -> candidate value embedding
cs = candidate_pair[0].squeeze(0)
cv = candidate_pair[1].squeeze(0)
metrics_out = {
'mc': [],
'mr': []
}
for element in prev_sysout:
ts, tv, tq, metric = None, None, None, None
# slot-value pair case with a list containing two tensors
if isinstance(element, list):
ts = element[0].squeeze(0)
tv = element[1].squeeze(0)
left_expr = torch.dot(cs, ts)
right_expr = torch.dot(cv, tv)
intermediate = torch.multiply(left_expr, right_expr)
request_metric = torch.multiply(intermediate, user_utt)
metric = request_metric
metrics_out['mr'].append(metric)
# slot case with one tensor
elif isinstance(element, torch.Tensor):
tq = element.squeeze(0)
# TODO: PASS OUTPUT FROM CNN
left_expr = torch.dot(cs, tq)
right_expr = user_utt
confirm_metric = torch.multiply(left_expr, right_expr)
metric = confirm_metric
metrics_out['mc'].append(metric)
# this should not happen but who knows
else:
raise ValueError('ERROR in ContextModeling.forward. '
'Input is not a tensor or tuple. \n')
return metrics_out