Skip to content

Commit 154b4eb

Browse files
jimmodpgeorge
authored andcommitted
py: Implement "common word" compression scheme for error messages.
The idea here is that there's a moderate amount of ROM used up by exception text. Obviously we try to keep the messages short, and the code can enable terse errors, but it still adds up. Listed below is the total string data size for various ports: bare-arm 2860 minimal 2876 stm32 8926 (PYBV11) cc3200 3751 esp32 5721 This commit implements compression of these strings. It takes advantage of the fact that these strings are all 7-bit ascii and extracts the top 128 frequently used words from the messages and stores them packed (dropping their null-terminator), then uses (0x80 | index) inside strings to refer to these common words. Spaces are automatically added around words, saving more bytes. This happens transparently in the build process, mirroring the steps that are used to generate the QSTR data. The MP_COMPRESSED_ROM_TEXT macro wraps any literal string that should compressed, and it's automatically decompressed in mp_decompress_rom_string. There are many schemes that could be used for the compression, and some are included in py/makecompresseddata.py for reference (space, Huffman, ngram, common word). Results showed that the common-word compression gets better results. This is before counting the increased cost of the Huffman decoder. This might be slightly counter-intuitive, but this data is extremely repetitive at a word-level, and the byte-level entropy coder can't quite exploit that as efficiently. Ideally one would combine both approaches, but for now the common-word approach is the one that is used. For additional comparison, the size of the raw data compressed with gzip and zlib is calculated, as a sort of proxy for a lower entropy bound. With this scheme we come within 15% on stm32, and 30% on bare-arm (i.e. we use x% more bytes than the data compressed with gzip -- not counting the code overhead of a decoder, and how this would be hypothetically implemented). The feature is disabled by default and can be enabled by setting MICROPY_ROM_TEXT_COMPRESSION at the Makefile-level.
1 parent 1921224 commit 154b4eb

7 files changed

Lines changed: 403 additions & 20 deletions

File tree

py/makecompresseddata.py

Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
from __future__ import print_function
2+
3+
import collections
4+
import re
5+
import sys
6+
7+
import gzip
8+
import zlib
9+
10+
11+
_COMPRESSED_MARKER = 0xFF
12+
13+
14+
def check_non_ascii(msg):
15+
for c in msg:
16+
if ord(c) >= 0x80:
17+
print(
18+
'Unable to generate compressed data: message "{}" contains a non-ascii character "{}".'.format(
19+
msg, c
20+
),
21+
file=sys.stderr,
22+
)
23+
sys.exit(1)
24+
25+
26+
# Replace <char><space> with <char | 0x80>.
27+
# Trival scheme to demo/test.
28+
def space_compression(error_strings):
29+
for line in error_strings:
30+
check_non_ascii(line)
31+
result = ""
32+
for i in range(len(line)):
33+
if i > 0 and line[i] == " ":
34+
result = result[:-1]
35+
result += "\\{:03o}".format(ord(line[i - 1]))
36+
else:
37+
result += line[i]
38+
error_strings[line] = result
39+
return None
40+
41+
42+
# Replace common words with <0x80 | index>.
43+
# Index is into a table of words stored as aaaaa<0x80|a>bbb<0x80|b>...
44+
# Replaced words are assumed to have spaces either side to avoid having to store the spaces in the compressed strings.
45+
def word_compression(error_strings):
46+
topn = collections.Counter()
47+
48+
for line in error_strings.keys():
49+
check_non_ascii(line)
50+
for word in line.split(" "):
51+
topn[word] += 1
52+
53+
# Order not just by frequency, but by expected saving. i.e. prefer a longer string that is used less frequently.
54+
def bytes_saved(item):
55+
w, n = item
56+
return -((len(w) + 1) * (n - 1))
57+
58+
top128 = sorted(topn.items(), key=bytes_saved)[:128]
59+
60+
index = [w for w, _ in top128]
61+
index_lookup = {w: i for i, w in enumerate(index)}
62+
63+
for line in error_strings.keys():
64+
result = ""
65+
need_space = False
66+
for word in line.split(" "):
67+
if word in index_lookup:
68+
result += "\\{:03o}".format(0b10000000 | index_lookup[word])
69+
need_space = False
70+
else:
71+
if need_space:
72+
result += " "
73+
need_space = True
74+
result += word
75+
error_strings[line] = result.strip()
76+
77+
return "".join(w[:-1] + "\\{:03o}".format(0b10000000 | ord(w[-1])) for w in index)
78+
79+
80+
# Replace chars in text with variable length bit sequence.
81+
# For comparison only (the table is not emitted).
82+
def huffman_compression(error_strings):
83+
# https://github.com/tannewt/huffman
84+
import huffman
85+
86+
all_strings = "".join(error_strings)
87+
cb = huffman.codebook(collections.Counter(all_strings).items())
88+
89+
for line in error_strings:
90+
b = "1"
91+
for c in line:
92+
b += cb[c]
93+
n = len(b)
94+
if n % 8 != 0:
95+
n += 8 - (n % 8)
96+
result = ""
97+
for i in range(0, n, 8):
98+
result += "\\{:03o}".format(int(b[i : i + 8], 2))
99+
if len(result) > len(line) * 4:
100+
result = line
101+
error_strings[line] = result
102+
103+
# TODO: This would be the prefix lengths and the table ordering.
104+
return "_" * (10 + len(cb))
105+
106+
107+
# Replace common N-letter sequences with <0x80 | index>, where
108+
# the common sequences are stored in a separate table.
109+
# This isn't very useful, need a smarter way to find top-ngrams.
110+
def ngram_compression(error_strings):
111+
topn = collections.Counter()
112+
N = 2
113+
114+
for line in error_strings.keys():
115+
check_non_ascii(line)
116+
if len(line) < N:
117+
continue
118+
for i in range(0, len(line) - N, N):
119+
topn[line[i : i + N]] += 1
120+
121+
def bytes_saved(item):
122+
w, n = item
123+
return -(len(w) * (n - 1))
124+
125+
top128 = sorted(topn.items(), key=bytes_saved)[:128]
126+
127+
index = [w for w, _ in top128]
128+
index_lookup = {w: i for i, w in enumerate(index)}
129+
130+
for line in error_strings.keys():
131+
result = ""
132+
for i in range(0, len(line) - N + 1, N):
133+
word = line[i : i + N]
134+
if word in index_lookup:
135+
result += "\\{:03o}".format(0b10000000 | index_lookup[word])
136+
else:
137+
result += word
138+
if len(line) % N != 0:
139+
result += line[len(line) - len(line) % N :]
140+
error_strings[line] = result.strip()
141+
142+
return "".join(index)
143+
144+
145+
def main(collected_path, fn):
146+
error_strings = {}
147+
max_uncompressed_len = 0
148+
num_uses = 0
149+
150+
# Read in all MP_ERROR_TEXT strings.
151+
with open(collected_path, "r") as f:
152+
for line in f:
153+
line = line.strip()
154+
if not line:
155+
continue
156+
num_uses += 1
157+
error_strings[line] = None
158+
max_uncompressed_len = max(max_uncompressed_len, len(line))
159+
160+
# So that objexcept.c can figure out how big the buffer needs to be.
161+
print("#define MP_MAX_UNCOMPRESSED_TEXT_LEN ({})".format(max_uncompressed_len))
162+
163+
# Run the compression.
164+
compressed_data = fn(error_strings)
165+
166+
# Print the data table.
167+
print('MP_COMPRESSED_DATA("{}")'.format(compressed_data))
168+
169+
# Print the replacements.
170+
for uncomp, comp in error_strings.items():
171+
print('MP_MATCH_COMPRESSED("{}", "\\{:03o}{}")'.format(uncomp, _COMPRESSED_MARKER, comp))
172+
173+
# Used to calculate the "true" length of the (escaped) compressed strings.
174+
def unescape(s):
175+
return re.sub(r"\\\d\d\d", "!", s)
176+
177+
# Stats. Note this doesn't include the cost of the decompressor code.
178+
uncomp_len = sum(len(s) + 1 for s in error_strings.keys())
179+
comp_len = sum(1 + len(unescape(s)) + 1 for s in error_strings.values())
180+
data_len = len(compressed_data) + 1 if compressed_data else 0
181+
print("// Total input length: {}".format(uncomp_len))
182+
print("// Total compressed length: {}".format(comp_len))
183+
print("// Total data length: {}".format(data_len))
184+
print("// Predicted saving: {}".format(uncomp_len - comp_len - data_len))
185+
186+
# Somewhat meaningless comparison to zlib/gzip.
187+
all_input_bytes = "\\0".join(error_strings.keys()).encode()
188+
print()
189+
if hasattr(gzip, "compress"):
190+
gzip_len = len(gzip.compress(all_input_bytes)) + num_uses * 4
191+
print("// gzip length: {}".format(gzip_len))
192+
print("// Percentage of gzip: {:.1f}%".format(100 * (comp_len + data_len) / gzip_len))
193+
if hasattr(zlib, "compress"):
194+
zlib_len = len(zlib.compress(all_input_bytes)) + num_uses * 4
195+
print("// zlib length: {}".format(zlib_len))
196+
print("// Percentage of zlib: {:.1f}%".format(100 * (comp_len + data_len) / zlib_len))
197+
198+
199+
if __name__ == "__main__":
200+
main(sys.argv[1], word_compression)

py/makeqstrdefs.py

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,27 @@
1313
import os
1414

1515

16+
# Extract MP_QSTR_FOO macros.
17+
_MODE_QSTR = "qstr"
18+
19+
# Extract MP_COMPRESSED_ROM_TEXT("") macros. (Which come from MP_ERROR_TEXT)
20+
_MODE_COMPRESS = "compress"
21+
22+
1623
def write_out(fname, output):
1724
if output:
1825
for m, r in [("/", "__"), ("\\", "__"), (":", "@"), ("..", "@@")]:
1926
fname = fname.replace(m, r)
20-
with open(args.output_dir + "/" + fname + ".qstr", "w") as f:
27+
with open(args.output_dir + "/" + fname + "." + args.mode, "w") as f:
2128
f.write("\n".join(output) + "\n")
2229

2330

2431
def process_file(f):
2532
re_line = re.compile(r"#[line]*\s\d+\s\"([^\"]+)\"")
26-
re_qstr = re.compile(r"MP_QSTR_[_a-zA-Z0-9]+")
33+
if args.mode == _MODE_QSTR:
34+
re_match = re.compile(r"MP_QSTR_[_a-zA-Z0-9]+")
35+
elif args.mode == _MODE_COMPRESS:
36+
re_match = re.compile(r'MP_COMPRESSED_ROM_TEXT\("([^"]*)"\)')
2737
output = []
2838
last_fname = None
2939
for line in f:
@@ -41,9 +51,12 @@ def process_file(f):
4151
output = []
4252
last_fname = fname
4353
continue
44-
for match in re_qstr.findall(line):
45-
name = match.replace("MP_QSTR_", "")
46-
output.append("Q(" + name + ")")
54+
for match in re_match.findall(line):
55+
if args.mode == _MODE_QSTR:
56+
name = match.replace("MP_QSTR_", "")
57+
output.append("Q(" + name + ")")
58+
elif args.mode == _MODE_COMPRESS:
59+
output.append(match)
4760

4861
write_out(last_fname, output)
4962
return ""
@@ -56,7 +69,7 @@ def cat_together():
5669
hasher = hashlib.md5()
5770
all_lines = []
5871
outf = open(args.output_dir + "/out", "wb")
59-
for fname in glob.glob(args.output_dir + "/*.qstr"):
72+
for fname in glob.glob(args.output_dir + "/*." + args.mode):
6073
with open(fname, "rb") as f:
6174
lines = f.readlines()
6275
all_lines += lines
@@ -73,8 +86,11 @@ def cat_together():
7386
old_hash = f.read()
7487
except IOError:
7588
pass
89+
mode_full = "QSTR"
90+
if args.mode == _MODE_COMPRESS:
91+
mode_full = "Compressed data"
7692
if old_hash != new_hash:
77-
print("QSTR updated")
93+
print(mode_full, "updated")
7894
try:
7995
# rename below might fail if file exists
8096
os.remove(args.output_file)
@@ -84,22 +100,27 @@ def cat_together():
84100
with open(args.output_file + ".hash", "w") as f:
85101
f.write(new_hash)
86102
else:
87-
print("QSTR not updated")
103+
print(mode_full, "not updated")
88104

89105

90106
if __name__ == "__main__":
91-
if len(sys.argv) != 5:
92-
print("usage: %s command input_filename output_dir output_file" % sys.argv[0])
107+
if len(sys.argv) != 6:
108+
print("usage: %s command mode input_filename output_dir output_file" % sys.argv[0])
93109
sys.exit(2)
94110

95111
class Args:
96112
pass
97113

98114
args = Args()
99115
args.command = sys.argv[1]
100-
args.input_filename = sys.argv[2]
101-
args.output_dir = sys.argv[3]
102-
args.output_file = sys.argv[4]
116+
args.mode = sys.argv[2]
117+
args.input_filename = sys.argv[3] # Unused for command=cat
118+
args.output_dir = sys.argv[4]
119+
args.output_file = None if len(sys.argv) == 5 else sys.argv[5] # Unused for command=split
120+
121+
if args.mode not in (_MODE_QSTR, _MODE_COMPRESS):
122+
print("error: mode %s unrecognised" % sys.argv[2])
123+
sys.exit(2)
103124

104125
try:
105126
os.makedirs(args.output_dir)

py/misc.h

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,4 +257,58 @@ typedef union _mp_float_union_t {
257257

258258
#endif // MICROPY_PY_BUILTINS_FLOAT
259259

260+
/** ROM string compression *************/
261+
262+
#ifdef NO_QSTR
263+
264+
// QSTR extraction sets NO_QSTR.
265+
// So leave MP_COMPRESSED_ROM_TEXT in place for makeqstrdefs.py / makecompresseddata.py to find them.
266+
267+
// However, dynamic native modules also set NO_QSTR, so provide a dummy implementation.
268+
#if MICROPY_ENABLE_DYNRUNTIME
269+
typedef const char *mp_rom_error_text_t;
270+
#define MP_COMPRESSED_ROM_TEXT(x) x
271+
#endif
272+
273+
#else
274+
275+
#if MICROPY_ROM_TEXT_COMPRESSION
276+
277+
// Force usage of the MP_ERROR_TEXT macro by requiring an opaque type.
278+
typedef struct {} *mp_rom_error_text_t;
279+
280+
// Regular build -- map MP_COMPRESSED_ROM_TEXT to the compressed strings.
281+
282+
#include <string.h>
283+
284+
inline __attribute__((always_inline)) const char *MP_COMPRESSED_ROM_TEXT(const char *msg) {
285+
// "genhdr/compressed.data.h" contains an invocation of the MP_MATCH_COMPRESSED macro for each compressed string.
286+
// The giant if(strcmp) tree is optimized by the compiler, which turns this into a direct return of the compressed data.
287+
#define MP_MATCH_COMPRESSED(a, b) if (strcmp(msg, a) == 0) { return b; } else
288+
289+
// It also contains a single invocation of the MP_COMPRESSED_DATA macro, we don't need that here.
290+
#define MP_COMPRESSED_DATA(x)
291+
292+
#include "genhdr/compressed.data.h"
293+
294+
#undef MP_COMPRESSED_DATA
295+
#undef MP_MATCH_COMPRESSED
296+
297+
return msg;
298+
}
299+
300+
#else
301+
302+
// Compression not enabled, just make it a no-op.
303+
typedef const char *mp_rom_error_text_t;
304+
#define MP_COMPRESSED_ROM_TEXT(x) x
305+
306+
#endif // MICROPY_ROM_TEXT_COMPRESSION
307+
308+
#endif // NO_QSTR
309+
310+
// Might add more types of compressed text in the future.
311+
// For now, forward directly to MP_COMPRESSED_ROM_TEXT.
312+
#define MP_ERROR_TEXT(x) (mp_rom_error_text_t)MP_COMPRESSED_ROM_TEXT(x)
313+
260314
#endif // MICROPY_INCLUDED_PY_MISC_H

0 commit comments

Comments
 (0)