natural language toolkit ibm model core c 20012023 nltk project tah wei hoon hoon twgmail com url https www nltk org for license information see license txt common methods and classes for all ibm models see ibmmodel1 ibmmodel2 ibmmodel3 ibmmodel4 and ibmmodel5 for specific implementations the ibm models are a series of generative models that learn lexical translation probabilities ptarget language wordsource language word given a sentencealigned parallel corpus the models increase in sophistication from model 1 to 5 typically the output of lower models is used to seed the higher models all models use the expectationmaximization em algorithm to learn various probability tables words in a sentence are oneindexed the first word of a sentence has position 1 not 0 index 0 is reserved in the source sentence for the null token the concept of position does not apply to null but it is indexed at 0 by convention each target word is aligned to exactly one source word or the null token references philipp koehn 2010 statistical machine translation cambridge university press new york peter e brown stephen a della pietra vincent j della pietra and robert l mercer 1993 the mathematics of statistical machine translation parameter estimation computational linguistics 19 2 263311 param sentencealignedcorpus parallel corpus under consideration type sentencealignedcorpus listalignedsent return number of words in the longest target language sentence of sentencealignedcorpus abstract base class for all ibm models avoid division by zero and precision errors by imposing a minimum value for probabilities note that this approach is theoretically incorrect since it may create probabilities that sum to more than 1 in practice the contribution of probabilities with minprob is tiny enough that the value of minprob can be treated as zero dictstrstr float probabilitytarget word source word values accessed as translationtabletargetwordsourceword dictintintintint float probabilityi j l m values accessed as alignmenttableijlm used in model 2 and hill climbing in models 3 and above dictintstr float probabilityfertility source word values accessed as fertilitytablefertilitysourceword used in model 3 and higher probability that a generated word requires another target word that is aligned to null used in model 3 and higher initialize probability tables to a uniform distribution derived classes should implement this accordingly add the null token setstr all source language words used in training setstr all target language words used in training sample the most probable alignments from the entire alignment space first determine the best alignment according to ibm model 2 with this initial alignment use hill climbing to determine the best alignment according to a higher ibm model add this alignment and its neighbors to the sample set repeat this process with other initial alignments obtained by pegging an alignment point hill climbing may be stuck in a local maxima hence the pegging and trying out of different alignments param sentencepair source and target language sentence pair to generate a sample of alignments from type sentencepair alignedsent return a set of best alignments represented by their alignmentinfo and the best alignment of the set for convenience rtype setalignmentinfo alignmentinfo start from the best model 2 alignment start from other model 2 alignments with the constraint that j is aligned pegged to i finds the best alignment according to ibm model 2 used as a starting point for hill climbing in models 3 and above because it is easier to compute than the best alignments in higher models param sentencepair source and target language sentence pair to be wordaligned type sentencepair alignedsent param jpegged if specified the alignment point of jpegged will be fixed to ipegged type jpegged int param ipegged alignment point to jpegged type ipegged int use the pegged alignment instead of searching for best one starting from the alignment in alignmentinfo look at neighboring alignments iteratively for the best one there is no guarantee that the best alignment in the alignment space will be found because the algorithm might be stuck in a local maximum param jpegged if specified the search will be constrained to alignments where jpegged remains unchanged type jpegged int return the best alignment found from hill climbing rtype alignmentinfo until there are no better alignments determine the neighbors of alignmentinfo obtained by moving or swapping one alignment point param jpegged if specified neighbors that have a different alignment point from jpegged will not be considered type jpegged int return a set neighboring alignments represented by their alignmentinfo rtype setalignmentinfo add alignments that differ by one alignment point update alignment update cepts add alignments that have two alignment points swapped update alignments update cepts clip p1 if it is too large because p0 1 p1 should not be smaller than minprob probability of target sentence and an alignment given the source sentence all required information is assumed to be in alignmentinfo and self derived classes should override this method helper data object for training ibm models 3 and up readonly for a source sentence and its counterpart in the target language this class holds information about the sentence pair s alignment cepts and fertility warning alignments are oneindexed here in contrast to nltk translate alignment and alignedsent which are zeroindexed this class is not meant to be used outside of ibm models tupleint alignment function alignmentj is the position in the source sentence that is aligned to the position j in the target sentence tuplestr source sentence referred to by this object should include null token none in index 0 tuplestr target sentence referred to by this object should have a dummy element in index 0 so that the first word starts from index 1 listlistint the positions of the target words in ascending order aligned to a source word position for example cepts4 2 3 7 means that words in positions 2 3 and 7 of the target sentence are aligned to the word in position 4 of the source sentence float optional probability of alignment as defined by the ibm model that assesses this alignment fertility of word in position i of the source sentence return whether the word in position j of the target sentence is a head word return the ceiling of the average positions of the words in the tablet of cept i or 0 if i is none return the previous cept of j or none if j belongs to the first cept return the position of the previous word that is in the same tablet as j or none if j is the first word of the tablet return zeroindexed alignment suitable for use in external nltk translate modules like nltk translate alignment rtype listtuple data object to store counts of various parameters during training natural language toolkit ibm model core c 2001 2023 nltk project tah wei hoon hoon tw gmail com url https www nltk org for license information see license txt common methods and classes for all ibm models see ibmmodel1 ibmmodel2 ibmmodel3 ibmmodel4 and ibmmodel5 for specific implementations the ibm models are a series of generative models that learn lexical translation probabilities p target language word source language word given a sentence aligned parallel corpus the models increase in sophistication from model 1 to 5 typically the output of lower models is used to seed the higher models all models use the expectation maximization em algorithm to learn various probability tables words in a sentence are one indexed the first word of a sentence has position 1 not 0 index 0 is reserved in the source sentence for the null token the concept of position does not apply to null but it is indexed at 0 by convention each target word is aligned to exactly one source word or the null token references philipp koehn 2010 statistical machine translation cambridge university press new york peter e brown stephen a della pietra vincent j della pietra and robert l mercer 1993 the mathematics of statistical machine translation parameter estimation computational linguistics 19 2 263 311 param sentence_aligned_corpus parallel corpus under consideration type sentence_aligned_corpus list alignedsent return number of words in the longest target language sentence of sentence_aligned_corpus abstract base class for all ibm models avoid division by zero and precision errors by imposing a minimum value for probabilities note that this approach is theoretically incorrect since it may create probabilities that sum to more than 1 in practice the contribution of probabilities with min_prob is tiny enough that the value of min_prob can be treated as zero giza is more liberal and uses 1 0e 7 dict str str float probability target word source word values accessed as translation_table target_word source_word dict int int int int float probability i j l m values accessed as alignment_table i j l m used in model 2 and hill climbing in models 3 and above dict int str float probability fertility source word values accessed as fertility_table fertility source_word used in model 3 and higher probability that a generated word requires another target word that is aligned to null used in model 3 and higher initialize probability tables to a uniform distribution derived classes should implement this accordingly add the null token set str all source language words used in training set str all target language words used in training sample the most probable alignments from the entire alignment space first determine the best alignment according to ibm model 2 with this initial alignment use hill climbing to determine the best alignment according to a higher ibm model add this alignment and its neighbors to the sample set repeat this process with other initial alignments obtained by pegging an alignment point hill climbing may be stuck in a local maxima hence the pegging and trying out of different alignments param sentence_pair source and target language sentence pair to generate a sample of alignments from type sentence_pair alignedsent return a set of best alignments represented by their alignmentinfo and the best alignment of the set for convenience rtype set alignmentinfo alignmentinfo start from the best model 2 alignment start from other model 2 alignments with the constraint that j is aligned pegged to i finds the best alignment according to ibm model 2 used as a starting point for hill climbing in models 3 and above because it is easier to compute than the best alignments in higher models param sentence_pair source and target language sentence pair to be word aligned type sentence_pair alignedsent param j_pegged if specified the alignment point of j_pegged will be fixed to i_pegged type j_pegged int param i_pegged alignment point to j_pegged type i_pegged int 1 indexed exclude null init all alignments to null init all cepts to empty list use the pegged alignment instead of searching for best one starting from the alignment in alignment_info look at neighboring alignments iteratively for the best one there is no guarantee that the best alignment in the alignment space will be found because the algorithm might be stuck in a local maximum param j_pegged if specified the search will be constrained to alignments where j_pegged remains unchanged type j_pegged int return the best alignment found from hill climbing rtype alignmentinfo alias with shorter name until there are no better alignments determine the neighbors of alignment_info obtained by moving or swapping one alignment point param j_pegged if specified neighbors that have a different alignment point from j_pegged will not be considered type j_pegged int return a set neighboring alignments represented by their alignmentinfo rtype set alignmentinfo exclude null add alignments that differ by one alignment point update alignment update cepts add alignments that have two alignment points swapped update alignments update cepts clip p1 if it is too large because p0 1 p1 should not be smaller than min_prob probability of target sentence and an alignment given the source sentence all required information is assumed to be in alignment_info and self derived classes should override this method helper data object for training ibm models 3 and up read only for a source sentence and its counterpart in the target language this class holds information about the sentence pair s alignment cepts and fertility warning alignments are one indexed here in contrast to nltk translate alignment and alignedsent which are zero indexed this class is not meant to be used outside of ibm models tuple int alignment function alignment j is the position in the source sentence that is aligned to the position j in the target sentence tuple str source sentence referred to by this object should include null token none in index 0 tuple str target sentence referred to by this object should have a dummy element in index 0 so that the first word starts from index 1 list list int the positions of the target words in ascending order aligned to a source word position for example cepts 4 2 3 7 means that words in positions 2 3 and 7 of the target sentence are aligned to the word in position 4 of the source sentence float optional probability of alignment as defined by the ibm model that assesses this alignment fertility of word in position i of the source sentence return whether the word in position j of the target sentence is a head word return the ceiling of the average positions of the words in the tablet of cept i or 0 if i is none return the previous cept of j or none if j belongs to the first cept return the position of the previous word that is in the same tablet as j or none if j is the first word of the tablet return zero indexed alignment suitable for use in external nltk translate modules like nltk translate alignment rtype list tuple alignment to null token data object to store counts of various parameters during training
from bisect import insort_left
from collections import defaultdict
from copy import deepcopy
from math import ceil


def longest_target_sentence_length(sentence_aligned_corpus):
    
    max_m = 0
    for aligned_sentence in sentence_aligned_corpus:
        m = len(aligned_sentence.words)
        max_m = max(m, max_m)
    return max_m


class IBMModel:
    

    
    
    
    
    
    MIN_PROB = 1.0e-12  

    def __init__(self, sentence_aligned_corpus):
        self.init_vocab(sentence_aligned_corpus)
        self.reset_probabilities()

    def reset_probabilities(self):
        self.translation_table = defaultdict(
            lambda: defaultdict(lambda: IBMModel.MIN_PROB)
        )
        

        self.alignment_table = defaultdict(
            lambda: defaultdict(
                lambda: defaultdict(lambda: defaultdict(lambda: IBMModel.MIN_PROB))
            )
        )
        

        self.fertility_table = defaultdict(lambda: defaultdict(lambda: self.MIN_PROB))
        

        self.p1 = 0.5
        

    def set_uniform_probabilities(self, sentence_aligned_corpus):
        
        pass

    def init_vocab(self, sentence_aligned_corpus):
        src_vocab = set()
        trg_vocab = set()
        for aligned_sentence in sentence_aligned_corpus:
            trg_vocab.update(aligned_sentence.words)
            src_vocab.update(aligned_sentence.mots)
        
        src_vocab.add(None)

        self.src_vocab = src_vocab
        

        self.trg_vocab = trg_vocab
        

    def sample(self, sentence_pair):
        
        sampled_alignments = set()
        l = len(sentence_pair.mots)
        m = len(sentence_pair.words)

        
        initial_alignment = self.best_model2_alignment(sentence_pair)
        potential_alignment = self.hillclimb(initial_alignment)
        sampled_alignments.update(self.neighboring(potential_alignment))
        best_alignment = potential_alignment

        
        
        for j in range(1, m + 1):
            for i in range(0, l + 1):
                initial_alignment = self.best_model2_alignment(sentence_pair, j, i)
                potential_alignment = self.hillclimb(initial_alignment, j)
                neighbors = self.neighboring(potential_alignment, j)
                sampled_alignments.update(neighbors)
                if potential_alignment.score > best_alignment.score:
                    best_alignment = potential_alignment

        return sampled_alignments, best_alignment

    def best_model2_alignment(self, sentence_pair, j_pegged=None, i_pegged=0):
        
        src_sentence = [None] + sentence_pair.mots
        trg_sentence = ["UNUSED"] + sentence_pair.words  

        l = len(src_sentence) - 1  
        m = len(trg_sentence) - 1

        alignment = [0] * (m + 1)  
        cepts = [[] for i in range(l + 1)]  

        for j in range(1, m + 1):
            if j == j_pegged:
                
                best_i = i_pegged
            else:
                best_i = 0
                max_alignment_prob = IBMModel.MIN_PROB
                t = trg_sentence[j]

                for i in range(0, l + 1):
                    s = src_sentence[i]
                    alignment_prob = (
                        self.translation_table[t][s] * self.alignment_table[i][j][l][m]
                    )

                    if alignment_prob >= max_alignment_prob:
                        max_alignment_prob = alignment_prob
                        best_i = i

            alignment[j] = best_i
            cepts[best_i].append(j)

        return AlignmentInfo(
            tuple(alignment), tuple(src_sentence), tuple(trg_sentence), cepts
        )

    def hillclimb(self, alignment_info, j_pegged=None):
        
        alignment = alignment_info  
        max_probability = self.prob_t_a_given_s(alignment)

        while True:
            old_alignment = alignment
            for neighbor_alignment in self.neighboring(alignment, j_pegged):
                neighbor_probability = self.prob_t_a_given_s(neighbor_alignment)

                if neighbor_probability > max_probability:
                    alignment = neighbor_alignment
                    max_probability = neighbor_probability

            if alignment == old_alignment:
                
                break

        alignment.score = max_probability
        return alignment

    def neighboring(self, alignment_info, j_pegged=None):
        
        neighbors = set()

        l = len(alignment_info.src_sentence) - 1  
        m = len(alignment_info.trg_sentence) - 1
        original_alignment = alignment_info.alignment
        original_cepts = alignment_info.cepts

        for j in range(1, m + 1):
            if j != j_pegged:
                
                for i in range(0, l + 1):
                    new_alignment = list(original_alignment)
                    new_cepts = deepcopy(original_cepts)
                    old_i = original_alignment[j]

                    
                    new_alignment[j] = i

                    
                    insort_left(new_cepts[i], j)
                    new_cepts[old_i].remove(j)

                    new_alignment_info = AlignmentInfo(
                        tuple(new_alignment),
                        alignment_info.src_sentence,
                        alignment_info.trg_sentence,
                        new_cepts,
                    )
                    neighbors.add(new_alignment_info)

        for j in range(1, m + 1):
            if j != j_pegged:
                
                for other_j in range(1, m + 1):
                    if other_j != j_pegged and other_j != j:
                        new_alignment = list(original_alignment)
                        new_cepts = deepcopy(original_cepts)
                        other_i = original_alignment[other_j]
                        i = original_alignment[j]

                        
                        new_alignment[j] = other_i
                        new_alignment[other_j] = i

                        
                        new_cepts[other_i].remove(other_j)
                        insort_left(new_cepts[other_i], j)
                        new_cepts[i].remove(j)
                        insort_left(new_cepts[i], other_j)

                        new_alignment_info = AlignmentInfo(
                            tuple(new_alignment),
                            alignment_info.src_sentence,
                            alignment_info.trg_sentence,
                            new_cepts,
                        )
                        neighbors.add(new_alignment_info)

        return neighbors

    def maximize_lexical_translation_probabilities(self, counts):
        for t, src_words in counts.t_given_s.items():
            for s in src_words:
                estimate = counts.t_given_s[t][s] / counts.any_t_given_s[s]
                self.translation_table[t][s] = max(estimate, IBMModel.MIN_PROB)

    def maximize_fertility_probabilities(self, counts):
        for phi, src_words in counts.fertility.items():
            for s in src_words:
                estimate = counts.fertility[phi][s] / counts.fertility_for_any_phi[s]
                self.fertility_table[phi][s] = max(estimate, IBMModel.MIN_PROB)

    def maximize_null_generation_probabilities(self, counts):
        p1_estimate = counts.p1 / (counts.p1 + counts.p0)
        p1_estimate = max(p1_estimate, IBMModel.MIN_PROB)
        
        
        self.p1 = min(p1_estimate, 1 - IBMModel.MIN_PROB)

    def prob_of_alignments(self, alignments):
        probability = 0
        for alignment_info in alignments:
            probability += self.prob_t_a_given_s(alignment_info)
        return probability

    def prob_t_a_given_s(self, alignment_info):
        
        return 0.0


class AlignmentInfo:
    

    def __init__(self, alignment, src_sentence, trg_sentence, cepts):
        if not isinstance(alignment, tuple):
            raise TypeError(
                "The alignment must be a tuple because it is used "
                "to uniquely identify AlignmentInfo objects."
            )

        self.alignment = alignment
        

        self.src_sentence = src_sentence
        

        self.trg_sentence = trg_sentence
        

        self.cepts = cepts
        

        self.score = None
        

    def fertility_of_i(self, i):
        
        return len(self.cepts[i])

    def is_head_word(self, j):
        
        i = self.alignment[j]
        return self.cepts[i][0] == j

    def center_of_cept(self, i):
        
        if i is None:
            return 0

        average_position = sum(self.cepts[i]) / len(self.cepts[i])
        return int(ceil(average_position))

    def previous_cept(self, j):
        
        i = self.alignment[j]
        if i == 0:
            raise ValueError(
                "Words aligned to NULL cannot have a previous "
                "cept because NULL has no position"
            )
        previous_cept = i - 1
        while previous_cept > 0 and self.fertility_of_i(previous_cept) == 0:
            previous_cept -= 1

        if previous_cept <= 0:
            previous_cept = None
        return previous_cept

    def previous_in_tablet(self, j):
        
        i = self.alignment[j]
        tablet_position = self.cepts[i].index(j)
        if tablet_position == 0:
            return None
        return self.cepts[i][tablet_position - 1]

    def zero_indexed_alignment(self):
        
        zero_indexed_alignment = []
        for j in range(1, len(self.trg_sentence)):
            i = self.alignment[j] - 1
            if i < 0:
                i = None  
            zero_indexed_alignment.append((j - 1, i))
        return zero_indexed_alignment

    def __eq__(self, other):
        return self.alignment == other.alignment

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        return hash(self.alignment)


class Counts:
    

    def __init__(self):
        self.t_given_s = defaultdict(lambda: defaultdict(lambda: 0.0))
        self.any_t_given_s = defaultdict(lambda: 0.0)
        self.p0 = 0.0
        self.p1 = 0.0
        self.fertility = defaultdict(lambda: defaultdict(lambda: 0.0))
        self.fertility_for_any_phi = defaultdict(lambda: 0.0)

    def update_lexical_translation(self, count, alignment_info, j):
        i = alignment_info.alignment[j]
        t = alignment_info.trg_sentence[j]
        s = alignment_info.src_sentence[i]
        self.t_given_s[t][s] += count
        self.any_t_given_s[s] += count

    def update_null_generation(self, count, alignment_info):
        m = len(alignment_info.trg_sentence) - 1
        fertility_of_null = alignment_info.fertility_of_i(0)
        self.p1 += fertility_of_null * count
        self.p0 += (m - 2 * fertility_of_null) * count

    def update_fertility(self, count, alignment_info):
        for i in range(0, len(alignment_info.src_sentence)):
            s = alignment_info.src_sentence[i]
            phi = alignment_info.fertility_of_i(i)
            self.fertility[phi][s] += count
            self.fertility_for_any_phi[s] += count