Compare LM on Spelling Correction#

This tutorial is available as an IPython notebook at Malaya/example/compare-lm-spelling-correction.

Malaya got 3 different LM models,

  1. KenLM

  2. GPT2

  3. Masked LM

So we are going to compare the spelling correction results.

[1]:
import os

os.environ['CUDA_VISIBLE_DEVICES'] = ''
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
[2]:
import malaya
/home/husein/.local/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.
  warn("The installed version of bitsandbytes was compiled without GPU support. "
/home/husein/.local/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32
/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3397
  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))
/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3927
  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))
[3]:
# some text examples copied from Twitter

string1 = 'krajaan patut bagi pencen awal skt kpd warga emas supaya emosi'
string2 = 'Husein ska mkn aym dkat kampng Jawa'
string3 = 'Melayu malas ni narration dia sama je macam men are trash. True to some, false to some.'
string4 = 'Tapi tak pikir ke bahaya perpetuate myths camtu. Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah. Your kids will be victims of that too.'
string5 = 'DrM cerita Melayu malas semenjak saya kat University (early 1980s) and now as i am edging towards retirement in 4-5 years time after a career of being an Engineer, Project Manager, General Manager'
string6 = 'blh bntg dlm kls nlp sy, nnti intch'
string7 = 'mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik'

Load probability model#

def load(
    language_model=None,
    sentence_piece: bool = False,
    stemmer=None,
    **kwargs,
):
    """
    Load a Probability Spell Corrector.

    Parameters
    ----------
    language_model: Callable, optional (default=None)
        If not None, must an object with `score` method.
    sentence_piece: bool, optional (default=False)
        if True, reduce possible augmentation states using sentence piece.
    stemmer: Callable, optional (default=None)
        a Callable object, must have `stem_word` method.

    Returns
    -------
    result: model
        List of model classes:

        * if passed `language_model` will return `malaya.spelling_correction.probability.ProbabilityLM`.
        * else will return `malaya.spelling_correction.probability.Probability`.
    """
[4]:
kenlm = malaya.language_model.kenlm()
kenlm
[4]:
<Model from b'model.klm'>
[5]:
malaya.language_model.available_mlm
[5]:
{'mesolitica/bert-base-standard-bahasa-cased': {'Size (MB)': 310},
 'mesolitica/bert-tiny-standard-bahasa-cased': {'Size (MB)': 66.1},
 'mesolitica/roberta-base-standard-bahasa-cased': {'Size (MB)': 443},
 'mesolitica/roberta-tiny-standard-bahasa-cased': {'Size (MB)': 66.1}}
[6]:
bert_base = malaya.language_model.mlm(model = 'mesolitica/bert-base-standard-bahasa-cased')
roberta_base = malaya.language_model.mlm(model = 'mesolitica/roberta-base-standard-bahasa-cased')
Loading the tokenizer from the `special_tokens_map.json` and the `added_tokens.json` will be removed in `transformers 5`,  it is kept for forward compatibility, but it is recommended to update your `tokenizer_config.json` by uploading it again. You will see the new `added_tokens_decoder` attribute that will store the relevant information.
[7]:
malaya.language_model.available_gpt2
[7]:
{'mesolitica/gpt2-117m-bahasa-cased': {'Size (MB)': 454}}
[8]:
gpt2 = malaya.language_model.gpt2(model = 'mesolitica/gpt2-117m-bahasa-cased')
You are resizing the embedding layer without providing a `pad_to_multiple_of` parameter. This means that the new embedding dimension will be 32001. This might induce some performance reduction as *Tensor Cores* will not be available. For more details about this, or help on choosing the correct value for resizing, refer to this guide: https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc
[9]:
model_kenlm = malaya.spelling_correction.probability.load(language_model = kenlm)
[10]:
model_bert_base = malaya.spelling_correction.probability.load(language_model = bert_base)
[11]:
model_roberta_base = malaya.spelling_correction.probability.load(language_model = roberta_base)
[12]:
model_gpt2 = malaya.spelling_correction.probability.load(language_model = gpt2)

To correct a sentence#

def correct_text(
    self,
    text: str,
    lookback: int = 3,
    lookforward: int = 3,
):
    """
    Correct all the words within a text, returning the corrected text.

    Parameters
    ----------
    text: str
    lookback: int, optional (default=3)
        N words on the left hand side.
        if put -1, will take all words on the left hand side.
        longer left hand side will take longer to compute.
    lookforward: int, optional (default=3)
        N words on the right hand side.
        if put -1, will take all words on the right hand side.
        longer right hand side will take longer to compute.

    Returns
    -------
    result: str
    """
[13]:
strings = [string1, string2, string3, string4, string5, string6, string7]
[14]:
tokenizer = malaya.tokenizer.Tokenizer()
[15]:
for s in strings:
    tokenized = tokenizer.tokenize(s)
    print('original:', s)
    print('corrected:', model_kenlm.correct_text(' '.join(tokenized)))
    print()
original: krajaan patut bagi pencen awal skt kpd warga emas supaya emosi
corrected: kerajaan patut bagi pencen awal sikit kpd warga emas supaya emosi

original: Husein ska mkn aym dkat kampng Jawa
corrected: Husin ska makan ayam dekat kampung Jawa

original: Melayu malas ni narration dia sama je macam men are trash. True to some, false to some.
corrected: Melayu malas ni narration dia sama je macam men are trash . True to some , false to some .

original: Tapi tak pikir ke bahaya perpetuate myths camtu. Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah. Your kids will be victims of that too.
corrected: Tapi tak pikir ke bahaya perpetuate myths camtu . Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah . Your kids will be victims of that too .

original: DrM cerita Melayu malas semenjak saya kat University (early 1980s) and now as i am edging towards retirement in 4-5 years time after a career of being an Engineer, Project Manager, General Manager
corrected: DrM cerita Melayu malas semenjak saya kat University ( early 1980s ) and now has i am edging towards retirement ini 4 - 5 years time after a career of being ini Engineer , Project Manager , General Manager

original: blh bntg dlm kls nlp sy, nnti intch
corrected: blh bintang dlm kelas nlp saya , nnti intch

original: mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik
corrected: mulakan slh org boleh , bila geng tuh kena salahkan jgk xboleh trima . . pelik

[16]:
for s in strings:
    tokenized = tokenizer.tokenize(s)
    print('original:', s)
    print('corrected:', model_bert_base.correct_text(' '.join(tokenized)))
    print()
original: krajaan patut bagi pencen awal skt kpd warga emas supaya emosi
corrected: kerajaan patut bagi pencen awal sikit kpd warga emas supaya emosi

original: Husein ska mkn aym dkat kampng Jawa
corrected: Husin ska mkn ayam dekat kampung Jawa

original: Melayu malas ni narration dia sama je macam men are trash. True to some, false to some.
corrected: Melayu malas ni narration dia sama je macam men are trash . True to some , false to some .

original: Tapi tak pikir ke bahaya perpetuate myths camtu. Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah. Your kids will be victims of that too.
corrected: Tapi tak pikir ke bahaya perpetuate myths camtu . Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah . Your kids will be victims of that too .

original: DrM cerita Melayu malas semenjak saya kat University (early 1980s) and now as i am edging towards retirement in 4-5 years time after a career of being an Engineer, Project Manager, General Manager
corrected: DrM cerita Melayu malas semenjak saya kat University ( early 1980s ) and now has i am edging towards retirement vin 4 - 5 years time after a career of being ini Engineer , Project Manager , General Manager

original: blh bntg dlm kls nlp sy, nnti intch
corrected: blh bantang dlm kelas nlp sya , nnti intch

original: mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik
corrected: mulakan slh org boleh , bila geng tuh kena salahkan jgk xboleh trima . . pelik

[17]:
for s in strings:
    tokenized = tokenizer.tokenize(s)
    print('original:', s)
    print('corrected:', model_roberta_base.correct_text(' '.join(tokenized)))
    print()
original: krajaan patut bagi pencen awal skt kpd warga emas supaya emosi
corrected: kerjaan patut bagi pencen awal sikit kpd warga emas supaya emosi

original: Husein ska mkn aym dkat kampng Jawa
corrected: Hussein ska mkn ayam dekat kampung Jawa

original: Melayu malas ni narration dia sama je macam men are trash. True to some, false to some.
corrected: Melayu malas ni narration dia sama je macam men are trash . True to some , false to some .

original: Tapi tak pikir ke bahaya perpetuate myths camtu. Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah. Your kids will be victims of that too.
corrected: Tapi tak pikir ke bahaya perpetuate myths camtu . Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah . Your kids will be victims of that too .

original: DrM cerita Melayu malas semenjak saya kat University (early 1980s) and now as i am edging towards retirement in 4-5 years time after a career of being an Engineer, Project Manager, General Manager
corrected: DrM cerita Melayu malas semenjak saya kat University ( early 1980s ) and now has i am edging towards retirement ini 4 - 5 years time after a career of being ini Engineer , Project Manager , General Manager

original: blh bntg dlm kls nlp sy, nnti intch
corrected: blh bentang dlm kelas nlp saya , nnti intch

original: mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik
corrected: mulakan slh org boleh , bila geng tuh kena salahkan jgk xboleh trima . . pelik

[18]:
for s in strings:
    tokenized = tokenizer.tokenize(s)
    print('original:', s)
    print('corrected:', model_gpt2.correct_text(' '.join(tokenized)))
    print()
original: krajaan patut bagi pencen awal skt kpd warga emas supaya emosi
corrected: kerajaan patut bagi pencen awal sikit kpd warga emas supaya emosi

original: Husein ska mkn aym dkat kampng Jawa
corrected: Husen ska mkn ayam dekat kampung Jawa

original: Melayu malas ni narration dia sama je macam men are trash. True to some, false to some.
corrected: Melayu malas ni narration dia sama je macam men are trash . True to some , false to some .

original: Tapi tak pikir ke bahaya perpetuate myths camtu. Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah. Your kids will be victims of that too.
corrected: Tapi tak pikir ke bahaya perpetuate myths camtu . Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah . Your kids will be victims of that too .

original: DrM cerita Melayu malas semenjak saya kat University (early 1980s) and now as i am edging towards retirement in 4-5 years time after a career of being an Engineer, Project Manager, General Manager
corrected: DrM cerita Melayu malas semenjak saya kat University ( early 1980s ) and now has i am edging towards retirement ini 4 - 5 years time after a career of being ane Engineer , Project Manager , General Manager

original: blh bntg dlm kls nlp sy, nnti intch
corrected: blh binatang dlm kelas nlp saya , nnti intch

original: mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik
corrected: mulakan slh org boleh , bila geng tuh kena salahkan jgk xboleh trima . . pelik

[ ]: