Update.
[picoclvr.git] / graph.py
1 #!/usr/bin/env python
2
3 import math
4
5 import torch, torchvision
6
7 from torch import nn
8 from torch.nn import functional as F
9
10 import cairo
11
12
13 ######################################################################
14 def save_attention_image(
15     filename,
16     tokens_input,
17     tokens_output,
18     attention,
19     n_sample=0,
20     n_head=0,
21     pixel_scale=8,
22     token_gap=10,
23     layer_gap=25,
24     y_eps=0.5,
25     padding=10,
26     min_att=0,
27     k_top=None,
28 ):
29     attention = torch.cat(
30         [x[n_sample : n_sample + 1, n_head] for x in attention], dim=0
31     )
32
33     if k_top is not None:
34         attention = attention * (
35             attention.sort(dim=-1, descending=True).indices < k_top
36         )
37
38     surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, None)
39
40     ctx = cairo.Context(surface)
41     ctx.scale(pixel_scale, pixel_scale)
42
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)
46
47     x, y = 0, 0
48
49     for d in range(attention.size(0)):
50         at = attention[d]
51         ni = torch.arange(at.size(0))[:, None].expand_as(at)
52         nj = torch.arange(at.size(1))[None, :].expand_as(at)
53         at = at.flatten()
54         o = at.sort().indices
55         at = at[o]
56         ni = ni.flatten()[o]
57         nj = nj.flatten()[o]
58         for i, j, a in zip(ni, nj, at):
59             if a > 0 and a >= min_att:
60                 c = 1 - a.item()
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)
65                 ctx.stroke()
66         y -= layer_gap
67
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)
73             ctx.fill()
74             ctx.set_source_rgb(0.0, 0.0, 0.0)
75             ctx.arc(xc, yc, token_gap / 20, 0, 2 * math.pi)
76             ctx.fill()
77
78     ctx.set_source_rgb(0.0, 0.0, 0.0)
79
80     for k, t in enumerate(tokens_input):
81         s = str(t)
82         (
83             x_bearing,
84             y_bearing,
85             width_t,
86             height_t,
87             x_advance,
88             y_advance,
89         ) = ctx.text_extents(s)
90         ctx.move_to(k * token_gap - width_t / 2, token_gap / 5 - y_bearing)
91         ctx.show_text(s)
92
93     for k, t in enumerate(tokens_output):
94         s = str(t)
95         (
96             x_bearing,
97             y_bearing,
98             width_t,
99             height_t,
100             x_advance,
101             y_advance,
102         ) = ctx.text_extents(s)
103         ctx.move_to(
104             k * token_gap - width_t / 2, -token_gap / 5 - attention.size(0) * layer_gap
105         )
106         ctx.show_text(s)
107
108     x, y, width, height = surface.ink_extents()
109     x -= padding
110     y -= padding
111     width += 2 * padding
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)
116     ctx_pdf.paint()
117     pdf_surface.finish()
118
119
120 ######################################################################
121
122 if __name__ == "__main__":
123     import mygpt
124
125     tokens_output = ["bluh", 2, 3, 4, "blih"]
126     tokens_input = ["n/a"] + tokens_output[:-1]
127
128     vocabulary_size = 3
129     x = torch.randint(vocabulary_size, (1, len(tokens_input)))
130
131     model = mygpt.MyGPT(
132         vocabulary_size=vocabulary_size,
133         dim_model=4,
134         dim_keys=2,
135         dim_hidden=2,
136         nb_heads=2,
137         nb_blocks=3,
138         dropout=0.1,
139         causal=True,
140     )
141
142     model.eval()
143     model.record_attention()
144
145     y1 = model(mygpt.BracketedSequence(x)).x
146
147     attention = model.retrieve_attention()
148
149     save_attention_image("attention.pdf", tokens_input, tokens_output, attention)