iTranslated by AI
Accelerating MeCab Word Segmentation with Parallel Processing
Motivation
MeCab allows for easy word segmentation (wakati-gaki) of text files from the command line as follows.
mecab -Owakati ./wiki.txt -o ./wiki-out.txt
However, this cannot be parallelized, so processing large text files takes quite a while.
As a test, I measured the time using the time command on Japanese Wikipedia (3.1 GiB), and the results were as follows.
time mecab -Owakati ./wiki.txt -o ./wiki-out.txt
________________________________________________________
Executed in 571.49 secs fish external
usr time 537.57 secs 982.00 micros 537.57 secs
sys time 29.01 secs 432.00 micros 29.01 secs
Taking nearly 10 minutes is quite painful, so I want to speed it up.
While there are articles about speeding up MeCab by processing multiple files in parallel, I couldn't find any articles discussing speedup for a single file, so I'm recording this as a memorandum of various things I tried.
Experiments were conducted in an environment with a 12-core, 24-thread CPU.
Update: 2021-07-18
I was informed on Twitter about parallel processing using the parallel command, so I have added it to the end of this article.
Conclusion
I managed to handle it by writing the following bash script.
The file is split into segments, word segmentation is performed in parallel for each file, and then the output files are merged after being sorted.
mkdir -p ./tmp
split -a 4 -l 500000 -d --additional-suffix .txt wiki.txt ./tmp/wiki-
find ./tmp -name 'wiki-*.txt' | xargs -l -P $(nproc) -I {} mecab -Owakati {} -o {}.out
cat `find ./tmp -name 'wiki-*.txt.out' | sort` > wiki-out.txt
rm -r ./tmp
The results are as follows, and I was able to speed it up by about 8 times.
time bash run.sh
________________________________________________________
Executed in 77.23 secs fish external
usr time 643.31 secs 1119.00 micros 643.31 secs
sys time 77.29 secs 497.00 micros 77.29 secs
Since file I/O can become a bottleneck, be careful in environments with slow read/write speeds such as NFS. In such cases, it might be better to try the parallel processing using Python shown in the next section.
There might be even better ways, so if you have any ideas, please let me know in the comments.
Trial and Error
multiprocessing with Python
MeCab has a Python wrapper library, so it seems like we can control parallel processing nicely from Python.
Writing a straightforward multi-process script using Python's multiprocessing module would look like the following.
This assumes that the text file for word segmentation is in the current directory.
import os
import MeCab
from multiprocessing import Pool
from pathlib import Path
def run(text):
mecab = MeCab.Tagger("-Owakati")
return mecab.parse(text)
def main():
with Path("./wiki.txt").open() as f, Path("./wiki-out.txt").open("w") as w:
with Pool(processes=os.cpu_count()) as pool:
for sentence in pool.imap(run, f):
w.write(sentence+"\n")
if __name__ == "__main__":
main()
Since the Tagger class instance is not picklable, I tried initializing it within each process. However, this is extremely slow because the Tagger class is initialized for every single line. It was pointless.
The measurement results are as follows. It became much slower.
time poetry run python src/parallel-mecab-1.py
________________________________________________________
Executed in 22.04 mins fish external
usr time 199.72 mins 0.00 micros 199.72 mins
sys time 252.65 mins 1376.00 micros 252.65 mins
multiprocessing with Python (Memory-loaded version)
Next, I wrote the script as follows.
import os
import MeCab
from multiprocessing import Pool
from pathlib import Path
from more_itertools import divide
def run(text_iter):
mecab = MeCab.Tagger("-Owakati")
return [mecab.parse(text) for text in text_iter]
def main():
with Path("./wiki.txt").open() as f, Path("./wiki-out.txt").open("w") as w:
num_process = os.cpu_count()
with Pool(processes=num_process) as pool:
for sentences in pool.imap(run, divide(num_process, f)):
w.write("\n".join(sentences)+"\n")
if __name__ == "__main__":
main()
As a trade-off for holding the word segmentation results in memory, I initialized the Tagger only once within each process (matching the number of cores) and iterated through the loop.
The measurement results are as follows. It became significantly faster (about one-fifth of the original time), but it consumed an enormous amount of memory.
time poetry run python src/parallel-mecab-2.py
________________________________________________________
Executed in 100.06 secs fish external
usr time 630.11 secs 1579.00 micros 630.11 secs
sys time 60.04 secs 0.00 micros 60.04 secs
Messing around with split
Since running the script above consumes quite a bit of memory, I felt it would be better to manage things through file I/O, so I decided to write a script. I adopted the strategy of splitting the file using the split command, performing word segmentation with MeCab on each part, and then merging the resulting files after sorting them.
mkdir -p ./tmp
split -a 4 -n $(nproc) -d --additional-suffix .txt wiki.txt ./tmp/wiki-
find ./tmp -name 'wiki-*.txt' | xargs -l -P $(nproc) -I {} mecab -Owakati {} -o {}.out
cat `find ./tmp -name 'wiki-*.txt.out' | sort` > wiki-out.txt
rm -r ./tmp
The measurement results are as follows. It was quite fast and used almost no memory, but you should be careful that it consumes a fair amount of storage. Since file I/O can become the bottleneck, you might want to reconsider running this in environments with heavy Read/Write loads, such as NFS.
time bash run-1.sh
________________________________________________________
Executed in 84.26 secs fish external
usr time 643.91 secs 1.44 millis 643.90 secs
sys time 74.85 secs 0.61 millis 74.85 secs
...But having come this far, I realized that the split command was dividing the file by bytes. That won't work, so I'll adjust it a little.
Messing around with split (Improved version)
Therefore, I changed the split command to process the file line by line.
mkdir -p ./tmp
split -a 4 -l 500000 -d --additional-suffix .txt wiki.txt ./tmp/wiki-
find ./tmp -name 'wiki-*.txt' | xargs -l -P $(nproc) -I {} mecab -Owakati {} -o {}.out
cat `find ./tmp -name 'wiki-*.txt.out' | sort` > wiki-out.txt
rm -r ./tmp
time bash run-2.sh
________________________________________________________
Executed in 77.23 secs fish external
usr time 643.31 secs 1119.00 micros 643.31 secs
sys time 77.29 secs 497.00 micros 77.29 secs
The results look good too.
Update: Using the parallel command
After publishing this article, I was informed on Twitter that using the parallel command is a good option.
mkdir -p ./tmp
cat ./wiki.txt | parallel --blocksize 1073741824 -P $(nproc) --pipe -N 500000 --rpl '{##} $_=sprintf("%04d",$job->seq()-1)' 'mecab -Owakati -o ./tmp/wiki-out.{##}.txt'
cat `find ./tmp -name 'wiki-out.*.txt' | sort` > ./wiki-out.txt
rm -r ./tmp
With this processing method, it's great that you can eliminate the need for temporary input files created just for splitting, unlike when using split. The measurement results are below. It's fast.
time bash run-3.sh
________________________________________________________
Executed in 81.53 secs fish external
usr time 724.94 secs 746.00 micros 724.94 secs
sys time 88.04 secs 410.00 micros 88.04 secs
Discussion