5 import torch, torchvision
8 from torch.nn import functional as F
13 ######################################################################
16 def save_attention_image(
20 # An iterable set of BxHxTxT attention matrices
27 # do not draw links with a lesser attention
29 # draw only the strongest links necessary to reache
31 min_total_attention=None,
32 # draw only the top k links
38 for m in attention_matrices:
39 am.append(m * (m.sort(dim=-1, descending=True).indices < k_top))
40 attention_matrices = am
42 if min_total_attention is not None:
44 for m in attention_matrices:
46 m = 1 - (s.values.cumsum(-1) < 1 - min_total_attention).long()
47 b = m.new(m.size()).scatter_(dim=-1, index=s.indices, src=m)
50 surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, None)
52 ctx = cairo.Context(surface)
53 ctx.scale(pixel_scale, pixel_scale)
55 ctx.set_source_rgb(0.0, 0.0, 0.0)
56 ctx.set_font_size(4.0)
57 # ctx.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
61 ctx.set_line_width(0.25)
62 for d in range(len(attention_matrices)):
63 at = attention_matrices[d]
64 ni = torch.arange(at.size(0))[:, None].expand_as(at)
65 nj = torch.arange(at.size(1))[None, :].expand_as(at)
71 for i, j, a in zip(ni, nj, at):
72 if a > 0 and a >= min_link_attention:
74 ctx.set_source_rgb(c, c, c)
75 ax, ay = j * token_gap, y - y_eps
77 dx, dy = i * token_gap, y - layer_gap + y_eps
79 bx, by = ax, ay - layer_gap * 0.5
80 cx, cy = dx, dy + layer_gap * 0.5
81 ctx.curve_to(bx, by, cx, cy, dx, dy)
87 for d in range(0, len(attention_matrices) + 1):
89 attention_matrices[0].size(-1)
91 else attention_matrices[d - 1].size(-2)
94 xc, yc = n * token_gap, -d * layer_gap
95 ctx.set_source_rgb(1.0, 1.0, 1.0)
96 ctx.arc(xc, yc, token_gap / 10, 0, 2 * math.pi)
98 ctx.set_source_rgb(0.0, 0.0, 0.0)
99 ctx.arc(xc, yc, token_gap / 20, 0, 2 * math.pi)
102 ctx.set_source_rgb(0.0, 0.0, 0.0)
104 for k, t in enumerate(tokens_input):
113 ) = ctx.text_extents(s)
114 ctx.move_to(k * token_gap - width_t / 2, token_gap / 5 - y_bearing)
117 for k, t in enumerate(tokens_output):
126 ) = ctx.text_extents(s)
128 k * token_gap - width_t / 2,
129 -token_gap / 5 - len(attention_matrices) * layer_gap,
133 x, y, width, height = surface.ink_extents()
137 height += 2 * padding
138 pdf_surface = cairo.PDFSurface(filename, width, height)
139 ctx_pdf = cairo.Context(pdf_surface)
140 ctx_pdf.set_source_surface(surface, -x, -y)
145 ######################################################################
147 if __name__ == "__main__":
150 tokens_output = ["<wat>", 2, 3, 4, "<end>"]
151 tokens_input = [""] + tokens_output[:-1]
154 x = torch.randint(vocabulary_size, (1, len(tokens_input)))
157 vocabulary_size=vocabulary_size,
168 model.record_attention()
170 y1 = model(mygpt.BracketedSequence(x)).x
172 attention_matrices = [m[0, 0] for m in model.retrieve_attention()]
174 # attention_matrices = [ torch.rand(3,5), torch.rand(8,3), torch.rand(5,8) ]
175 # for a in attention_matrices: a=a/a.sum(-1,keepdim=True)
177 save_attention_image(
183 min_total_attention=0.9,