5 import torch, torchvision
8 from torch.nn import functional as F
13 ######################################################################
14 def save_attention_image(
29 attention = torch.cat(
30 [x[n_sample : n_sample + 1, n_head] for x in attention], dim=0
34 attention = attention * (
35 attention.sort(dim=-1, descending=True).indices < k_top
38 surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, None)
40 ctx = cairo.Context(surface)
41 ctx.scale(pixel_scale, pixel_scale)
43 ctx.set_source_rgb(0.0, 0.0, 0.0)
44 ctx.set_font_size(4.0)
45 # ctx.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
49 for d in range(attention.size(0)):
51 ni = torch.arange(at.size(0))[:, None].expand_as(at)
52 nj = torch.arange(at.size(1))[None, :].expand_as(at)
58 for i, j, a in zip(ni, nj, at):
59 if a > 0 and a >= min_att:
61 ctx.set_source_rgb(c, c, c)
62 ctx.set_line_width(0.5)
63 ctx.move_to(j * token_gap, y - y_eps)
64 ctx.line_to(i * token_gap, y - layer_gap + y_eps)
68 for d in range(0, attention.size(0) + 1):
69 for n in range(attention.size(-1)):
70 xc, yc = n * token_gap, -d * layer_gap
71 ctx.set_source_rgb(1.0, 1.0, 1.0)
72 ctx.arc(xc, yc, token_gap / 10, 0, 2 * math.pi)
74 ctx.set_source_rgb(0.0, 0.0, 0.0)
75 ctx.arc(xc, yc, token_gap / 20, 0, 2 * math.pi)
78 ctx.set_source_rgb(0.0, 0.0, 0.0)
80 for k, t in enumerate(tokens_input):
89 ) = ctx.text_extents(s)
90 ctx.move_to(k * token_gap - width_t / 2, token_gap / 5 - y_bearing)
93 for k, t in enumerate(tokens_output):
102 ) = ctx.text_extents(s)
104 k * token_gap - width_t / 2, -token_gap / 5 - attention.size(0) * layer_gap
108 x, y, width, height = surface.ink_extents()
112 height += 2 * padding
113 pdf_surface = cairo.PDFSurface(filename, width, height)
114 ctx_pdf = cairo.Context(pdf_surface)
115 ctx_pdf.set_source_surface(surface, -x, -y)
120 ######################################################################
122 if __name__ == "__main__":
125 tokens_output = ["bluh", 2, 3, 4, "blih"]
126 tokens_input = ["n/a"] + tokens_output[:-1]
129 x = torch.randint(vocabulary_size, (1, len(tokens_input)))
132 vocabulary_size=vocabulary_size,
143 model.record_attention()
145 y1 = model(mygpt.BracketedSequence(x)).x
147 attention = model.retrieve_attention()
149 save_attention_image("attention.pdf", tokens_input, tokens_output, attention)