Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/helpers/NoamSchedule.scala
/* Copyright 2017, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.helpers import org.platanios.tensorflow.api._ /** Noam scheduling method, similar to that proposed in: * [Attention is All You Need (Section 5.3)](https://arxiv.org/pdf/1706.03762.pdf). * * This method applies a scheduling function to a provided initial learning rate (i.e., `value`). It requires a * step value to be provided in it's application function, in order to compute the decayed learning rate. You may * simply pass a TensorFlow variable that you increment at each training step. * * The decayed value is computed as follows: * {{{ * decayed = value * 5000.0f * (hiddenSize ** -0.5f) * min((step + 1) * (warmUpSteps ** -1.5f), (step + 1) ** -0.5f) * }}} * * @param warmUpSteps Number of warm-up steps. * @param hiddenSize Hidden layers size in the attention model. * * @author Emmanouil Antonios Platanios */ class NoamSchedule protected ( val warmUpSteps: Int, val hiddenSize: Int, val name: String = "NoamSchedule" ) extends tf.train.Schedule[Float] { /** Applies the scheduling method to `value`, the current iteration in the optimization loop is `step` and returns the * result. * * @param value Value to change based on this schedule. * @param step Option containing current iteration in the optimization loop, if one has been provided. * @return Potentially modified value. * @throws IllegalArgumentException If the scheduling method requires a value for `step` but the provided option is * empty. */ @throws[IllegalArgumentException] override def apply[I: TF : IsIntOrLong]( value: Output[Float], step: Option[Variable[I]] ): Output[Float] = { if (step.isEmpty) throw new IllegalArgumentException("A step needs to be provided for the Noam scheduling method.") tf.nameScope(name) { val stepValue = step.get.value.toFloat val warmUpStepsValue = tf.constant[Int](warmUpSteps).toFloat val hiddenSizeValue = tf.constant[Int](hiddenSize).toFloat val linearWarmup = tf.minimum(1.0f, stepValue / warmUpStepsValue) val rsqrtDecay = tf.rsqrt(tf.maximum(stepValue, warmUpStepsValue)) val rsqrtHidden = hiddenSizeValue ** -0.5f value * linearWarmup * rsqrtDecay * rsqrtHidden // value * 5000.0f * (hiddenSizeValue ** -0.5f) * // tf.minimum((stepValue + 1) * (warmUpStepsValue ** -1.5f), (stepValue + 1) ** -0.5f) } } } object NoamSchedule { def apply( warmUpSteps: Int, hiddenSize: Int, name: String = "NoamSchedule" ): NoamSchedule = { new NoamSchedule(warmUpSteps, hiddenSize) } }
3,309
39.864198
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/BidirectionalRNNEncoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.symphony.mt.models.Utilities._ import org.platanios.symphony.mt.models.helpers.Common import org.platanios.symphony.mt.models.rnn.Utilities._ import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.tf.RNNTuple import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape, Zero} /** Bi-directional (i.e., left-to-right) RNN encoder. * * This encoder takes as input a source sequence in some language and returns a tuple containing: * - '''Output:''' Concatenated outputs (for each time step) of the forward RNN and the backward RNN. * - '''State:''' Sequence of last computed RNN states in layer order containing both the forward and the backward * states for each layer (e.g., `Seq(forwardState0, backwardState0, forwardState1, backwardState1, ...)`). * * @author Emmanouil Antonios Platanios */ class BidirectionalRNNEncoder[T: TF : IsNotQuantized, State: OutputStructure, StateShape]( val cell: Cell[T, State, StateShape], val numUnits: Int, val numLayers: Int, val residual: Boolean = false, val dropout: Float = 0.0f, val residualFn: Option[(Output[T], Output[T]) => Output[T]] = None )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape], evZeroState: Zero.Aux[State, StateShape] ) extends RNNEncoder[T, State]() { override def apply( sequences: Sequences[Int] )(implicit context: ModelConstructionContext): EncodedSequences[T, State] = { val wordEmbeddingsSize = context.parameterManager.wordEmbeddingsType.embeddingsSize var embeddedSequences = embedSrcSequences(sequences) if (wordEmbeddingsSize != numUnits) { val projectionWeights = context.parameterManager.get[Float]( "ProjectionToEncoderNumUnits", Shape(wordEmbeddingsSize, numUnits)) val projectedSequences = Common.matrixMultiply(embeddedSequences.sequences, projectionWeights) embeddedSequences = embeddedSequences.copy(sequences = projectedSequences) } val numResLayers = if (residual && numLayers > 1) numLayers - 1 else 0 // Build the forward RNN cell. val biCellFw = stackedCell[T, State, StateShape]( cell = cell, numInputs = embeddedSequences.sequences.shape(-1), numUnits = numUnits, numLayers = numLayers / 2, numResidualLayers = numResLayers / 2, dropout = dropout, residualFn = residualFn, seed = context.env.randomSeed, name = "StackedBiCellFw") // Build the backward RNN cell. val biCellBw = stackedCell[T, State, StateShape]( cell = cell, numInputs = embeddedSequences.sequences.shape(-1), numUnits = numUnits, numLayers = numLayers / 2, numResidualLayers = numResLayers / 2, dropout = dropout, residualFn = residualFn, seed = context.env.randomSeed, name = "StackedBiCellBw") val unmergedBiTuple = tf.bidirectionalDynamicRNN( cellFw = biCellFw, cellBw = biCellBw, input = embeddedSequences.sequences.castTo[T], initialStateFw = None, initialStateBw = None, timeMajor = false, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory, sequenceLengths = embeddedSequences.lengths, name = "BidirectionalLayers") val rnnTuple = RNNTuple( // The bidirectional RNN output is the concatenation of the forward and the backward RNN outputs. output = tf.concatenate(Seq(unmergedBiTuple._1.output, unmergedBiTuple._2.output), axis = -1), state = unmergedBiTuple._1.state.map(List(_)) .zipAll(unmergedBiTuple._2.state.map(List(_)), Nil, Nil) .flatMap(Function.tupled(_ ++ _))) EncodedSequences(rnnTuple, embeddedSequences.lengths) } }
4,530
41.745283
117
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/GNMTDecoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models._ import org.platanios.symphony.mt.models.decoders.{OutputLayer, ProjectionToWords} import org.platanios.symphony.mt.models.rnn.attention.RNNAttention import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.tf.RNNTuple import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape} import org.platanios.tensorflow.api.ops.Output import org.platanios.tensorflow.api.ops.rnn.attention.{Attention, AttentionWrapperCell, AttentionWrapperState} /** * @author Emmanouil Antonios Platanios */ class GNMTDecoder[T: TF : IsNotQuantized, State: OutputStructure, AttentionState: OutputStructure, StateShape, AttentionStateShape]( val cell: Cell[T, State, StateShape], override val numUnits: Int, val numLayers: Int, val numResLayers: Int, val attention: RNNAttention[T, AttentionState, AttentionStateShape], val residual: Boolean = false, val dropout: Float = 0.0f, val useNewAttention: Boolean = true, override val outputLayer: OutputLayer = ProjectionToWords )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape], evOutputToShapeAttentionState: OutputToShape.Aux[AttentionState, AttentionStateShape] ) extends RNNDecoder[T, State, (AttentionWrapperState[T, State, AttentionState], Seq[State]), ((StateShape, Shape, Shape, Seq[Shape], Seq[Shape], Seq[Attention.StateShape[AttentionStateShape]]), Seq[StateShape])](numUnits, outputLayer) { override protected def cellAndInitialState( encodedSequences: EncodedSequences[T, State], tgtSequences: Option[Sequences[Int]] )(implicit context: ModelConstructionContext): (GNMTDecoder.StackedCell[T, State, AttentionState, StateShape, AttentionStateShape], (AttentionWrapperState[T, State, AttentionState], Seq[State])) = { // RNN cells val cells = (0 until numLayers).foldLeft(Seq.empty[tf.RNNCell[Output[T], State, Shape, StateShape]])((cells, i) => { val cellNumInputs = if (i == 0) 2 * numUnits else cells(i - 1).outputShape.apply(-1) + numUnits cells :+ Utilities.cell[T, State, StateShape]( cell = cell, numInputs = cellNumInputs, numUnits = numUnits, dropout = dropout, residualFn = { if (i >= numLayers - numResLayers) { Some((i: Output[T], o: Output[T]) => { // This residual function can handle inputs and outputs of different sizes (due to attention). val oLastDim = tf.shape(o).slice(-1) val iLastDim = tf.shape(i).slice(-1) val actualInput = tf.split(i, tf.stack(Seq(oLastDim, iLastDim - oLastDim)), axis = -1).head actualInput.shape.assertIsCompatibleWith(o.shape) actualInput + o }) } else { None } }, device = context.nextDevice(), seed = context.env.randomSeed, name = s"Cell$i") }) // Attention val initialState = encodedSequences.rnnTuple.state val memory = Sequences( sequences = encodedSequences.rnnTuple.output, lengths = encodedSequences.lengths) val attentionCell = attention.createCell[State, StateShape]( cells.head, memory, numUnits, numUnits, useAttentionLayer = false, outputAttention = false) val attentionInitialState = attentionCell.initialState(initialState.head) val multiCell = new GNMTDecoder.StackedCell[T, State, AttentionState, StateShape, AttentionStateShape]( attentionCell, cells.tail, useNewAttention) (multiCell, (attentionInitialState, initialState.tail)) } } object GNMTDecoder { /** GNMT RNN cell that is composed by applying an attention cell and then a sequence of RNN cells in order, all being * fed the same attention as input. * * This means that the output of each RNN is fed to the next one as input, while the states remain separate. * Furthermore, the attention layer is used first as the bottom layer and then the same attention is fed to all upper * layers. That is either the previous attention, or the new attention generated by the bottom layer (if * `useNewAttention` is set to `true`). * * Note that this class does no variable management at all. Variable sharing should be handled based on the RNN cells * the caller provides to this class. The learn API provides a layer version of this class that also does some * management of the variables involved. * * @param attentionCell Attention cell to use. * @param cells Cells being stacked together. * @param useNewAttention Boolean value specifying whether to use the attention generated from the current step * bottom layer's output as input to all upper layers, or the previous attention (i.e., same * as the one that's input to the bottom layer). * @param name Name prefix used for all new ops. * * @author Emmanouil Antonios Platanios */ class StackedCell[T: TF : IsNotQuantized, State: OutputStructure, AttentionState: OutputStructure, StateShape, AttentionStateShape]( val attentionCell: AttentionWrapperCell[T, State, AttentionState, StateShape, AttentionStateShape], val cells: Seq[tf.RNNCell[Output[T], State, Shape, StateShape]], val useNewAttention: Boolean = false, val name: String = "GNMTStackedCell" )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape], evOutputToShapeAttentionState: OutputToShape.Aux[AttentionState, AttentionStateShape] ) extends tf.RNNCell[Output[T], (AttentionWrapperState[T, State, AttentionState], Seq[State]), Shape, ((StateShape, Shape, Shape, Seq[Shape], Seq[Shape], Seq[Attention.StateShape[AttentionStateShape]]), Seq[StateShape])] { override def outputShape: Shape = { cells.last.outputShape } override def stateShape: ((StateShape, Shape, Shape, Seq[Shape], Seq[Shape], Seq[Attention.StateShape[AttentionStateShape]]), Seq[StateShape]) = { (attentionCell.stateShape, cells.map(_.stateShape)) } override def forward( input: RNNTuple[Output[T], (AttentionWrapperState[T, State, AttentionState], Seq[State])] ): RNNTuple[Output[T], (AttentionWrapperState[T, State, AttentionState], Seq[State])] = { val minusOne = tf.constant(-1) val nextAttentionTuple = attentionCell(RNNTuple(input.output, input.state._1)) var currentInput = nextAttentionTuple.output val state = cells.zip(input.state._2).map { case (cell, s) => val concatenatedInput = { if (useNewAttention) tf.concatenate(Seq(currentInput, nextAttentionTuple.state.attention), axis = minusOne) else tf.concatenate(Seq(currentInput, input.state._1.attention), axis = minusOne) } val nextTuple = cell(RNNTuple(concatenatedInput, s)) currentInput = nextTuple.output nextTuple.state } RNNTuple(currentInput, (nextAttentionTuple.state, state)) } } }
7,749
50.324503
237
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/UnidirectionalRNNEncoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.symphony.mt.models.Utilities._ import org.platanios.symphony.mt.models.helpers.Common import org.platanios.symphony.mt.models.rnn.Utilities._ import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape, Zero} /** Uni-directional (i.e., left-to-right) RNN encoder. * * This encoder takes as input a source sequence in some language and returns a tuple containing: * - '''Output:''' Outputs (for each time step) of the RNN. * - '''State:''' Sequence of last computed RNN states in layer order containing the states for each layer * (e.g., `Seq(state0, state1, ...)`). * * @author Emmanouil Antonios Platanios */ class UnidirectionalRNNEncoder[T: TF : IsNotQuantized, State: OutputStructure, StateShape]( val cell: Cell[T, State, StateShape], val numUnits: Int, val numLayers: Int, val residual: Boolean = false, val dropout: Float = 0.0f, val residualFn: Option[(Output[T], Output[T]) => Output[T]] = None )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape], evZeroState: Zero.Aux[State, StateShape] ) extends RNNEncoder[T, State]() { override def apply( sequences: Sequences[Int] )(implicit context: ModelConstructionContext): EncodedSequences[T, State] = { val wordEmbeddingsSize = context.parameterManager.wordEmbeddingsType.embeddingsSize var embeddedSequences = embedSrcSequences(sequences) if (wordEmbeddingsSize != numUnits) { val projectionWeights = context.parameterManager.get[Float]( "ProjectionToEncoderNumUnits", Shape(wordEmbeddingsSize, numUnits)) val projectedSequences = Common.matrixMultiply(embeddedSequences.sequences, projectionWeights) embeddedSequences = embeddedSequences.copy(sequences = projectedSequences) } val numResLayers = if (residual && numLayers > 1) numLayers - 1 else 0 val uniCell = stackedCell[T, State, StateShape]( cell = cell, numInputs = embeddedSequences.sequences.shape(-1), numUnits = numUnits, numLayers = numLayers, numResidualLayers = numResLayers, dropout = dropout, residualFn = residualFn, seed = context.env.randomSeed, name = "StackedUniCell") val rnnTuple = tf.dynamicRNN( cell = uniCell, input = embeddedSequences.sequences.castTo[T], initialState = None, timeMajor = false, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory, sequenceLengths = embeddedSequences.lengths, name = "UnidirectionalLayers") EncodedSequences(rnnTuple, embeddedSequences.lengths) } }
3,448
40.554217
109
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/RNNDecoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.symphony.mt.models.Transformation.Decoder import org.platanios.symphony.mt.models.decoders.{BasicDecoder, BeamSearchDecoder, OutputLayer} import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape} import org.platanios.tensorflow.api.tf.RNNCell /** * @author Emmanouil Antonios Platanios */ abstract class RNNDecoder[T: TF : IsNotQuantized, State, DecState: OutputStructure, DecStateShape]( val numUnits: Int, val outputLayer: OutputLayer )(implicit protected val evOutputToShapeDecState: OutputToShape.Aux[DecState, DecStateShape] ) extends Decoder[EncodedSequences[T, State]] { override def applyTrain( encodedSequences: EncodedSequences[T, State] )(implicit context: ModelConstructionContext): Sequences[Float] = { // TODO: What if no target sequences are provided? val tgtSequences = context.tgtSequences.get // Shift the target sequence one step forward so the decoder learns to output the next word. val tgtBosId = tf.constant[Int](Vocabulary.BEGIN_OF_SEQUENCE_TOKEN_ID) val batchSize = tf.shape(tgtSequences.sequences).slice(0) val shiftedTgtSequences = tf.concatenate(Seq( tf.fill[Int, Int](tf.stack[Int](Seq(batchSize, 1)))(tgtBosId), tgtSequences.sequences), axis = 1) val shiftedTgtSequenceLengths = tgtSequences.lengths + 1 val (cell, initialState) = cellAndInitialState(encodedSequences, Some(tgtSequences)) // Embed the target sequences. val embeddedTgtSequences = embeddings(shiftedTgtSequences) // Decoder RNN val helper = BasicDecoder.TrainingHelper[Output[T], DecState, Shape]( input = embeddedTgtSequences, sequenceLengths = shiftedTgtSequenceLengths, timeMajor = false) val decoder = BasicDecoder(cell, initialState, helper, outputLayer[T](numUnits)) val tuple = decoder.decode( outputTimeMajor = false, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory) Sequences(tuple._1.modelOutput.toFloat, tuple._3) } override def applyInfer( encodedSequences: EncodedSequences[T, State] )(implicit context: ModelConstructionContext): Sequences[Int] = { val (cell, initialState) = cellAndInitialState(encodedSequences) // Determine the maximum allowed sequence length to consider while decoding. val maxDecodingLength = { if (!context.mode.isTraining && context.dataConfig.tgtMaxLength != -1) tf.constant(context.dataConfig.tgtMaxLength) else tf.round(tf.max(encodedSequences.lengths).toFloat * context.inferenceConfig.maxDecodingLengthFactor).toInt } // Create some constants that will be used during decoding. val tgtBosID = tf.constant[Int](Vocabulary.BEGIN_OF_SEQUENCE_TOKEN_ID) val tgtEosID = tf.constant[Int](Vocabulary.END_OF_SEQUENCE_TOKEN_ID) // Create the decoder RNN. val batchSize = tf.shape(encodedSequences.lengths).slice(0).expandDims(0) val embeddings = (ids: Output[Int]) => this.embeddings(ids) val output = { if (context.inferenceConfig.beamWidth > 1) { val decoder = BeamSearchDecoder( cell, initialState, embeddings, tf.fill[Int, Int](batchSize)(tgtBosID), tgtEosID, context.inferenceConfig.beamWidth, context.inferenceConfig.lengthPenalty, outputLayer[T](cell.outputShape.apply(-1))) val tuple = decoder.decode( outputTimeMajor = false, maximumIterations = maxDecodingLength, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory) Sequences(tuple._1.predictedIDs(---, 0), tuple._3(---, 0).toInt) } else { val decHelper = BasicDecoder.GreedyEmbeddingHelper[T, DecState]( embeddingFn = embeddings, beginTokens = tf.fill[Int, Int](batchSize)(tgtBosID), endToken = tgtEosID) val decoder = BasicDecoder(cell, initialState, decHelper, outputLayer[T](cell.outputShape.apply(-1))) val tuple = decoder.decode( outputTimeMajor = false, maximumIterations = maxDecodingLength, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory) Sequences(tuple._1.sample, tuple._3) } } // Make sure the outputs are of shape [batchSize, time] or [beamWidth, batchSize, time] // when using beam search. val outputSequences = { if (output.sequences.rank == 3) output.sequences.transpose(Tensor(2, 0, 1)) else output.sequences } Sequences(outputSequences(---, 0 :: -1), output.lengths - 1) } protected def embeddings( ids: Output[Int] )(implicit context: ModelConstructionContext): Output[T] = { context.parameterManager.wordEmbeddings(context.tgtLanguageID, ids).castTo[T] } protected def cellAndInitialState( encodedSequences: EncodedSequences[T, State], tgtSequences: Option[Sequences[Int]] = None )(implicit context: ModelConstructionContext): (RNNCell[Output[T], DecState, Shape, DecStateShape], DecState) }
5,966
42.875
111
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/package.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models import org.platanios.tensorflow.api.Output import org.platanios.tensorflow.api.tf.RNNTuple /** * @author Emmanouil Antonios Platanios */ package object rnn { case class EncodedSequences[T, State]( rnnTuple: RNNTuple[Output[T], Seq[State]], lengths: Output[Int]) }
961
32.172414
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/GNMTEncoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.symphony.mt.models.Utilities._ import org.platanios.symphony.mt.models.helpers.Common import org.platanios.symphony.mt.models.rnn.Utilities._ import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.tf.RNNTuple import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape, Zero} /** * @author Emmanouil Antonios Platanios */ class GNMTEncoder[T: TF : IsNotQuantized, State: OutputStructure, StateShape]( val cell: Cell[T, State, StateShape], val numUnits: Int, val numBiLayers: Int, val numUniLayers: Int, val numUniResLayers: Int, val dropout: Float = 0.0f, val residualFn: Option[(Output[T], Output[T]) => Output[T]] = None )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape], evZeroState: Zero.Aux[State, StateShape] ) extends RNNEncoder[T, State]() { override def apply( sequences: Sequences[Int] )(implicit context: ModelConstructionContext): EncodedSequences[T, State] = { val wordEmbeddingsSize = context.parameterManager.wordEmbeddingsType.embeddingsSize var embeddedSequences = embedSrcSequences(sequences) if (wordEmbeddingsSize != numUnits) { val projectionWeights = context.parameterManager.get[Float]( "ProjectionToEncoderNumUnits", Shape(wordEmbeddingsSize, numUnits)) val projectedSequences = Common.matrixMultiply(embeddedSequences.sequences, projectionWeights) embeddedSequences = embeddedSequences.copy(sequences = projectedSequences) } // Bidirectional RNN layers val biTuple = { if (numBiLayers > 0) { val biCellFw = stackedCell[T, State, StateShape]( cell = cell, numInputs = embeddedSequences.sequences.shape(-1), numUnits = numUnits, numLayers = numBiLayers, numResidualLayers = 0, dropout = dropout, residualFn = residualFn, seed = context.env.randomSeed, name = "StackedBiCellFw") val biCellBw = stackedCell[T, State, StateShape]( cell = cell, numInputs = embeddedSequences.sequences.shape(-1), numUnits = numUnits, numLayers = numBiLayers, numResidualLayers = 0, dropout = dropout, residualFn = residualFn, seed = context.env.randomSeed, name = "StackedBiCellBw") val unmergedBiTuple = tf.bidirectionalDynamicRNN( cellFw = biCellFw, cellBw = biCellBw, input = embeddedSequences.sequences.castTo[T], initialStateFw = None, initialStateBw = None, timeMajor = false, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory, sequenceLengths = embeddedSequences.lengths, name = "BidirectionalLayers") RNNTuple(tf.concatenate(Seq(unmergedBiTuple._1.output, unmergedBiTuple._2.output), -1), unmergedBiTuple._2.state) } else { RNNTuple(embeddedSequences.sequences.castTo[T], Seq.empty[State]) } } // Unidirectional RNN layers val uniCell = stackedCell[T, State, StateShape]( cell = cell, numInputs = biTuple.output.shape(-1), numUnits = numUnits, numLayers = numUniLayers, numResidualLayers = numUniResLayers, dropout = dropout, residualFn = residualFn, seed = context.env.randomSeed, name = "StackedUniCell") val uniTuple = tf.dynamicRNN( cell = uniCell, input = biTuple.output, initialState = None, timeMajor = false, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory, sequenceLengths = embeddedSequences.lengths, name = "UnidirectionalLayers") // Pass all of the encoder's state except for the first bi-directional layer's state, to the decoder. val rnnTuple = RNNTuple(uniTuple.output, biTuple.state ++ uniTuple.state) EncodedSequences(rnnTuple, embeddedSequences.lengths) } }
4,787
38.9
121
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/UnidirectionalRNNDecoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models._ import org.platanios.symphony.mt.models.decoders.{OutputLayer, ProjectionToWords} import org.platanios.symphony.mt.models.rnn.Utilities._ import org.platanios.symphony.mt.models.rnn.attention.RNNAttention import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape} import org.platanios.tensorflow.api.ops.Output import org.platanios.tensorflow.api.ops.rnn.attention.{Attention, AttentionWrapperCell, AttentionWrapperState} import org.platanios.tensorflow.api.ops.rnn.cell.RNNCell /** * @author Emmanouil Antonios Platanios */ class UnidirectionalRNNDecoder[T: TF : IsNotQuantized, State: OutputStructure, StateShape]( val cell: Cell[T, State, StateShape], override val numUnits: Int, val numLayers: Int, val residual: Boolean = false, val dropout: Float = 0.0f, val residualFn: Option[(Output[T], Output[T]) => Output[T]] = None, override val outputLayer: OutputLayer = ProjectionToWords )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape] ) extends RNNDecoder[T, State, Seq[State], Seq[StateShape]](numUnits, outputLayer) { override protected def cellAndInitialState( encodedSequences: EncodedSequences[T, State], tgtSequences: Option[Sequences[Int]] )(implicit context: ModelConstructionContext): (RNNCell[Output[T], Seq[State], Shape, Seq[StateShape]], Seq[State]) = { val numResLayers = if (residual && numLayers > 1) numLayers - 1 else 0 val uniCell = stackedCell[T, State, StateShape]( cell = cell, numInputs = numUnits, numUnits = numUnits, numLayers = numLayers, numResidualLayers = numResLayers, dropout = dropout, residualFn = residualFn, seed = context.env.randomSeed, name = "StackedUniCell") val initialState = encodedSequences.rnnTuple.state (uniCell, initialState) } } class UnidirectionalRNNDecoderWithAttention[T: TF : IsNotQuantized, State: OutputStructure, AttentionState: OutputStructure, StateShape, AttentionStateShape]( val cell: Cell[T, State, StateShape], override val numUnits: Int, val numLayers: Int, val attention: RNNAttention[T, AttentionState, AttentionStateShape], val residual: Boolean = false, val dropout: Float = 0.0f, val residualFn: Option[(Output[T], Output[T]) => Output[T]] = None, val outputAttention: Boolean = true, override val outputLayer: OutputLayer = ProjectionToWords )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape], evOutputToShapeAttentionState: OutputToShape.Aux[AttentionState, AttentionStateShape] ) extends RNNDecoder[T, State, AttentionWrapperState[T, Seq[State], AttentionState], (Seq[StateShape], Shape, Shape, Seq[Shape], Seq[Shape], Seq[Attention.StateShape[AttentionStateShape]])](numUnits, outputLayer) { override protected def cellAndInitialState( encodedSequences: EncodedSequences[T, State], tgtSequences: Option[Sequences[Int]] )(implicit context: ModelConstructionContext): (AttentionWrapperCell[T, Seq[State], AttentionState, Seq[StateShape], AttentionStateShape], AttentionWrapperState[T, Seq[State], AttentionState]) = { val numResLayers = if (residual && numLayers > 1) numLayers - 1 else 0 val uniCell = stackedCell[T, State, StateShape]( cell = cell, numInputs = numUnits + context.parameterManager.wordEmbeddingsType.embeddingsSize, numUnits = numUnits, numLayers = numLayers, numResidualLayers = numResLayers, dropout = dropout, residualFn = residualFn, seed = context.env.randomSeed, name = "StackedUniCell") val memory = Sequences( sequences = encodedSequences.rnnTuple.output, lengths = encodedSequences.lengths) val attentionCell = attention.createCell(uniCell, memory, numUnits, numUnits, useAttentionLayer = true, outputAttention) val initialState = attentionCell.initialState(encodedSequences.rnnTuple.state) (attentionCell, initialState) } }
4,734
46.828283
214
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/Cell.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape, Zero} import org.platanios.tensorflow.api.ops.rnn.cell._ /** * @author Emmanouil Antonios Platanios */ abstract class Cell[T: TF, State, StateShape](implicit val evOutputStructureState: OutputStructure[State], val evOutputToShapeState: OutputToShape.Aux[State, StateShape], val evZeroState: Zero.Aux[State, StateShape] ) { // The following two type aliases are used in the experiments module. type DataType = T type StateType = State type StateShapeType = StateShape def create( name: String, numInputs: Int, numUnits: Int )(implicit context: ModelConstructionContext): RNNCell[Output[T], State, Shape, StateShape] } case class GRU[T: TF : IsNotQuantized]( activation: Output[T] => Output[T] ) extends Cell[T, Output[T], Shape] { override def create( name: String, numInputs: Int, numUnits: Int )(implicit context: ModelConstructionContext): RNNCell[Output[T], Output[T], Shape, Shape] = { val gateKernel = context.parameterManager.get[T]("Gate/Weights", Shape(numInputs + numUnits, 2 * numUnits)) val gateBias = context.parameterManager.get[T]("Gate/Bias", Shape(2 * numUnits), tf.ZerosInitializer) val candidateKernel = context.parameterManager.get[T]("Candidate/Weights", Shape(numInputs + numUnits, numUnits)) val candidateBias = context.parameterManager.get[T]("Candidate/Bias", Shape(numUnits), tf.ZerosInitializer) GRUCell(gateKernel, gateBias, candidateKernel, candidateBias, activation, name) } } case class BasicLSTM[T: TF : IsNotQuantized]( activation: Output[T] => Output[T], forgetBias: Float = 1.0f ) extends Cell[T, LSTMState[T], (Shape, Shape)] { override def create( name: String, numInputs: Int, numUnits: Int )(implicit context: ModelConstructionContext): BasicLSTMCell[T] = { val kernel = context.parameterManager.get[T]("Weights", Shape(numInputs + numUnits, 4 * numUnits)) val bias = context.parameterManager.get[T]("Bias", Shape(4 * numUnits), tf.ZerosInitializer) BasicLSTMCell(kernel, bias, activation, forgetBias, name) } } case class LSTM[T: TF : IsNotQuantized]( activation: Output[T] => Output[T], forgetBias: Float = 1.0f, usePeepholes: Boolean = false, cellClip: Float = -1, projectionSize: Int = -1, projectionClip: Float = -1 ) extends Cell[T, LSTMState[T], (Shape, Shape)] { override def create( name: String, numInputs: Int, numUnits: Int )(implicit context: ModelConstructionContext): LSTMCell[T] = { val hiddenDepth = if (projectionSize != -1) projectionSize else numUnits val kernel = context.parameterManager.get[T]("Weights", Shape(numInputs + hiddenDepth, 4 * numUnits)) val bias = context.parameterManager.get[T]("Bias", Shape(4 * numUnits), tf.ZerosInitializer) val (wfDiag, wiDiag, woDiag) = { if (usePeepholes) { val wfDiag = context.parameterManager.get[T]("Peepholes/ForgetKernelDiag", Shape(numUnits)) val wiDiag = context.parameterManager.get[T]("Peepholes/InputKernelDiag", Shape(numUnits)) val woDiag = context.parameterManager.get[T]("Peepholes/OutputKernelDiag", Shape(numUnits)) (wfDiag, wiDiag, woDiag) } else { (null, null, null) } } val projectionKernel = { if (projectionSize != -1) context.parameterManager.get[T]("Projection/Weights", Shape(numUnits, projectionSize)) else null } LSTMCell( kernel, bias, activation, cellClip, wfDiag, wiDiag, woDiag, projectionKernel, projectionClip, forgetBias, name) } }
4,459
39.18018
117
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/RNNEncoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models.Transformation.Encoder /** * @author Emmanouil Antonios Platanios */ trait RNNEncoder[T, State] extends Encoder[EncodedSequences[T, State]]
867
35.166667
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/Utilities.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape} /** * @author Emmanouil Antonios Platanios */ object Utilities { def cell[T: TF : IsNotQuantized, State: OutputStructure, StateShape]( cell: Cell[T, State, StateShape], numInputs: Int, numUnits: Int, dropout: Float = 0.0f, residualFn: Option[(Output[T], Output[T]) => Output[T]] = None, device: String = "", seed: Option[Int] = None, name: String )(implicit context: ModelConstructionContext, evOutputToShape: OutputToShape.Aux[State, StateShape] ): tf.RNNCell[Output[T], State, Shape, StateShape] = { tf.variableScope(name) { tf.createWith(device = device) { // Create the main RNN cell. var createdCell = cell.create(name, numInputs, numUnits) // Optionally, apply dropout. if (dropout > 0.0f) { createdCell = tf.DropoutWrapper(createdCell, 1.0f - dropout, seed = seed, name = "Dropout") } // Add residual connections. createdCell = residualFn.map(tf.ResidualWrapper(createdCell, _)).getOrElse(createdCell) createdCell } } } def cells[T: TF : IsNotQuantized, State: OutputStructure, StateShape]( cell: Cell[T, State, StateShape], numInputs: Int, numUnits: Int, numLayers: Int, numResidualLayers: Int, dropout: Float = 0.0f, residualFn: Option[(Output[T], Output[T]) => Output[T]] = None, seed: Option[Int] = None, name: String )(implicit context: ModelConstructionContext, evOutputToShape: OutputToShape.Aux[State, StateShape] ): Seq[tf.RNNCell[Output[T], State, Shape, StateShape]] = { tf.variableScope(name) { (0 until numLayers).foldLeft(Seq.empty[tf.RNNCell[Output[T], State, Shape, StateShape]])((cells, i) => { val cellNumInputs = if (i == 0) numInputs else cells(i - 1).outputShape(-1) cells :+ this.cell[T, State, StateShape]( cell, cellNumInputs, numUnits, dropout, if (i >= numLayers - numResidualLayers) residualFn else None, context.nextDevice(), seed, s"Cell$i") }) } } def stackedCell[T: TF : IsNotQuantized, State: OutputStructure, StateShape]( cell: Cell[T, State, StateShape], numInputs: Int, numUnits: Int, numLayers: Int, numResidualLayers: Int, dropout: Float = 0.0f, residualFn: Option[(Output[T], Output[T]) => Output[T]] = None, seed: Option[Int] = None, name: String )(implicit context: ModelConstructionContext, evOutputToShape: OutputToShape.Aux[State, StateShape] ): tf.RNNCell[Output[T], Seq[State], Shape, Seq[StateShape]] = { tf.StackedCell(cells[T, State, StateShape]( cell, numInputs, numUnits, numLayers, numResidualLayers, dropout, residualFn, seed, name), name) } }
3,677
35.415842
110
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/attention/RNNAttention.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn.attention import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape} import org.platanios.tensorflow.api.ops.rnn.attention.AttentionWrapperCell /** * @author Emmanouil Antonios Platanios */ abstract class RNNAttention[T: TF : IsNotQuantized, AttentionState, AttentionStateShape] { def createCell[CellState: OutputStructure, CellStateShape]( cell: tf.RNNCell[Output[T], CellState, Shape, CellStateShape], memory: Sequences[T], numUnits: Int, inputSequencesLastAxisSize: Int, useAttentionLayer: Boolean, outputAttention: Boolean )(implicit context: ModelConstructionContext, evOutputToShapeCellState: OutputToShape.Aux[CellState, CellStateShape] ): AttentionWrapperCell[T, CellState, AttentionState, CellStateShape, AttentionStateShape] }
1,622
40.615385
92
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/attention/BahdanauRNNAttention.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn.attention import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape} import org.platanios.tensorflow.api.ops.rnn.attention.{Attention, AttentionWrapperCell} import org.platanios.tensorflow.api.ops.variables.{ConstantInitializer, ZerosInitializer} /** * @author Emmanouil Antonios Platanios */ class BahdanauRNNAttention[T: TF : IsDecimal]( val normalized: Boolean = false, val probabilityFn: Output[T] => Output[T], // TODO: Softmax should be the default. val scoreMask: Float = Float.NegativeInfinity.toFloat ) extends RNNAttention[T, Output[T], Shape] { override def createCell[CellState: OutputStructure, CellStateShape]( cell: tf.RNNCell[Output[T], CellState, Shape, CellStateShape], memory: Sequences[T], numUnits: Int, inputSequencesLastAxisSize: Int, useAttentionLayer: Boolean, outputAttention: Boolean )(implicit context: ModelConstructionContext, evOutputToShapeCellState: OutputToShape.Aux[CellState, CellStateShape] ): AttentionWrapperCell[T, CellState, Output[T], CellStateShape, Shape] = { tf.variableScope("BahdanauAttention") { val memoryWeights = context.parameterManager.get[T]("MemoryWeights", Shape(numUnits, numUnits)) val queryWeights = context.parameterManager.get[T]("QueryWeights", Shape(numUnits, numUnits)) val scoreWeights = context.parameterManager.get[T]("ScoreWeights", Shape(numUnits)) val (normFactor, normBias) = { if (normalized) { (context.parameterManager.get[T]("Factor", Shape(), ConstantInitializer(math.sqrt(1.0f / numUnits).toFloat)), context.parameterManager.get[T]("Bias", Shape(numUnits), ZerosInitializer)) } else { (null, null) } } val attention = tf.BahdanauAttention( tf.shape(memory.sequences).slice(1), memoryWeights, queryWeights, scoreWeights, probabilityFn, normFactor, normBias, scoreMask, "Attention") val attentionWeights = { if (useAttentionLayer) Seq(tf.variable[T]("AttentionWeights", Shape(numUnits + memory.sequences.shape(-1), numUnits), null).value) else null } tf.AttentionWrapperCell( cell, Seq(Attention.Memory(memory.sequences, Some(memory.lengths)) -> attention), attentionWeights, outputAttention = outputAttention) } } }
3,179
44.428571
119
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/rnn/attention/LuongRNNAttention.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.rnn.attention import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape} import org.platanios.tensorflow.api.ops.rnn.attention.{Attention, AttentionWrapperCell} import org.platanios.tensorflow.api.ops.variables.OnesInitializer /** * @author Emmanouil Antonios Platanios */ class LuongRNNAttention[T: TF : IsDecimal]( val scaled: Boolean = false, val probabilityFn: Output[T] => Output[T], // TODO: Softmax should be the default. val scoreMask: Float = Float.NegativeInfinity.toFloat ) extends RNNAttention[T, Output[T], Shape] { override def createCell[CellState: OutputStructure, CellStateShape]( cell: tf.RNNCell[Output[T], CellState, Shape, CellStateShape], memory: Sequences[T], numUnits: Int, inputSequencesLastAxisSize: Int, useAttentionLayer: Boolean, outputAttention: Boolean )(implicit context: ModelConstructionContext, evOutputToShapeCellState: OutputToShape.Aux[CellState, CellStateShape] ): AttentionWrapperCell[T, CellState, Output[T], CellStateShape, Shape] = { val memoryWeights = context.parameterManager.get[T]("MemoryWeights", Shape(memory.sequences.shape(-1), numUnits)) val scale = { if (scaled) context.parameterManager.get[T]("LuongFactor", Shape(), OnesInitializer) else null } val attention = tf.LuongAttention( tf.shape(memory.sequences).slice(1), memoryWeights, probabilityFn, scale, scoreMask, "Attention") val attentionWeights = { if (useAttentionLayer) Seq(context.parameterManager.get[T]("AttentionWeights", Shape(numUnits + memory.sequences.shape(-1), numUnits))) else null } tf.AttentionWrapperCell( cell, Seq(Attention.Memory(memory.sequences, Some(memory.lengths)) -> attention), attentionWeights, outputAttention = outputAttention) } }
2,669
41.380952
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/decoders/LengthPenalty.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.decoders import org.platanios.tensorflow.api._ /** Length penalty function to be used while decoding. */ trait LengthPenalty { def apply[T: TF : IsNotQuantized]( scores: Output[T], sequenceLengths: Output[Int] ): Output[T] } /** No length penalty. */ case object NoLengthPenalty extends LengthPenalty { override def apply[T: TF : IsNotQuantized]( scores: Output[T], sequenceLengths: Output[Int] ): Output[T] = { scores } } /** Exponential length penalty function. The penalty is equal to `sequenceLengths ^ alpha`, where all operations are * performed element-wise. * * @param alpha Length penalty weight (disabled if set to `0.0f`). */ case class ExponentialLengthPenalty(alpha: Float) extends LengthPenalty { override def apply[T: TF : IsNotQuantized]( scores: Output[T], sequenceLengths: Output[Int] ): Output[T] = { if (alpha == 0.0f) { scores } else { tf.nameScope("LengthPenalty") { val penaltyFactor = tf.constant(alpha, name = "PenaltyFactor").castTo[T] scores / (sequenceLengths.castTo[T] ^ penaltyFactor) } } } } /** Google length penalty function described in * [Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation](https://arxiv.org/abs/1609.08144.) * The penalty is equal to `((5 + sequenceLengths) / 6) ^ alpha`, where all operations are performed element-wise. * * @param alpha Length penalty weight (disabled if set to `0.0f`). */ case class GoogleLengthPenalty(alpha: Float) extends LengthPenalty { override def apply[T: TF : IsNotQuantized]( scores: Output[T], sequenceLengths: Output[Int] ): Output[T] = { if (alpha == 0.0f) { scores } else { tf.nameScope("LengthPenalty") { val five = tf.constant(5.0f, name = "Five").castTo[T] val six = tf.constant(6.0f, name = "Six").castTo[T] val lengths = sequenceLengths.castTo[T] val penaltyFactor = tf.constant(alpha, name = "PenaltyFactor").castTo[T] scores / tf.divide((five + lengths) ^ penaltyFactor, six ^ penaltyFactor) } } } }
2,834
33.156627
139
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/decoders/OutputLayer.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.decoders import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.models.helpers.Common import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ trait OutputLayer { def apply[T: TF : IsNotQuantized]( inputSize: Int )(implicit context: ModelConstructionContext): Output[T] => Output[T] } case object ProjectionToWords extends OutputLayer { override def apply[T: TF : IsNotQuantized]( inputSize: Int )(implicit context: ModelConstructionContext): Output[T] => Output[T] = { logits: Output[T] => { val outputWeights = context.parameterManager.getProjectionToWords(inputSize, context.tgtLanguageID).castTo[T] Common.matrixMultiply(logits, outputWeights) } } } case object ProjectionToWordEmbeddings extends OutputLayer { override def apply[T: TF : IsNotQuantized]( inputSize: Int )(implicit context: ModelConstructionContext): Output[T] => Output[T] = { logits: Output[T] => { val wordEmbeddingsSize = context.parameterManager.wordEmbeddingsType.embeddingsSize val outputWeights = context.parameterManager.get[T]( "ProjectionToWordEmbeddings", Shape(inputSize, wordEmbeddingsSize)) val projectedOutputs = Common.matrixMultiply(logits, outputWeights) val wordEmbeddings = context.parameterManager.wordEmbeddingsTable(context.tgtLanguageID).castTo[T] Common.matrixMultiply(projectedOutputs, wordEmbeddings, transposeY = true) } } }
2,179
37.928571
115
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/decoders/BasicDecoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.decoders import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.core.exception.InvalidShapeException import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape, Zero} import org.platanios.tensorflow.api.ops.rnn.RNN import org.platanios.tensorflow.api.utilities.DefaultsTo.IntDefault import scala.language.postfixOps /** Basic sampling Recurrent Neural Network (RNN) decoder. * * @param cell RNN cell to use for decoding. * @param initialCellState Initial RNN cell state to use for starting the decoding process. * @param helper Basic RNN decoder helper to use. * @param outputLayer Output layer to use that is applied at the outputs of the provided RNN cell before * returning them. * @param name Name prefix used for all created ops. * * @author Emmanouil Antonios Platanios */ class BasicDecoder[ Out: OutputStructure, State: OutputStructure, Sample: OutputStructure, OutShape, StateShape, SampleShape ]( override val cell: tf.RNNCell[Out, State, OutShape, StateShape], val initialCellState: State, val helper: BasicDecoder.Helper[Out, Sample, State], val outputLayer: Out => Out = (o: Out) => o, override val name: String = "BasicRNNDecoder" )(implicit evOutputToShapeOut: OutputToShape.Aux[Out, OutShape], evOutputToShapeState: OutputToShape.Aux[State, StateShape], evOutputToShapeSample: OutputToShape.Aux[Sample, SampleShape], evZeroOut: Zero.Aux[Out, OutShape], evZeroSample: Zero.Aux[Sample, SampleShape] ) extends Decoder[ /* Out */ Out, /* State */ State, /* DecOut */ BasicDecoder.BasicDecoderOutput[Out, Sample], /* DecState */ State, /* DecFinalOut */ BasicDecoder.BasicDecoderOutput[Out, Sample], /* DecFinalState */ State, /* Shapes */ OutShape, StateShape, (OutShape, SampleShape), StateShape]( cell = cell, name = name ) { /** Scalar tensor representing the batch size of the input values. */ override val batchSize: Output[Int] = { helper.batchSize } /** Returns a zero-valued output for this decoder. */ override def zeroOutput: BasicDecoder.BasicDecoderOutput[Out, Sample] = { val zeroOutput = Zero[Out].zero(batchSize, cell.outputShape, "ZeroOutput") BasicDecoder.BasicDecoderOutput( modelOutput = outputLayer(zeroOutput), sample = helper.zeroSample(batchSize, "ZeroSample")) } /** Returns the shape invariants for this decoder loop. * * @return Tuple containing: (i) the shape invariant for the "finished" signal, (ii) the decoder input shape * invariant, (iii) the decoder output shape invariant, and (iv) the decoder state shape invariant. */ override def shapeInvariants: (Shape, OutShape, (OutShape, SampleShape), StateShape) = { def _shapeConverter(shape: Shape): Shape = { val newShape = Array.fill[Int](shape.rank)(-1) newShape(0) = shape(0) if (shape.rank > 1) newShape(newShape.length - 1) = shape(shape.rank - 1) Shape(newShape) } val zeroOutput = this.zeroOutput val initialInput = helper.initialize()._2 val inputShapeInvariant = evOutputToShapeOut.shapeStructure.map( evOutputToShapeOut.shape(initialInput), _shapeConverter) val modelOutputShapeInvariant = evOutputToShapeOut.shapeStructure.map( evOutputToShapeOut.shape(zeroOutput.modelOutput), _shapeConverter) val sampleShapeInvariant = evOutputToShapeSample.shapeStructure.map( evOutputToShapeSample.shape(zeroOutput.sample), _shapeConverter) val cellStateShapeInvariant = evOutputToShapeState.shapeStructure.map( evOutputToShapeState.shape(initialCellState), _shapeConverter) (Shape(-1), inputShapeInvariant, (modelOutputShapeInvariant, sampleShapeInvariant), cellStateShapeInvariant) } /** This method is called before any decoding iterations. It computes the initial input values and the initial state. * * @return Tuple containing: (i) a scalar tensor specifying whether initialization has finished, * (ii) the next input, and (iii) the initial decoder state. */ override def initialize(): (Output[Boolean], Out, State) = { tf.nameScope(s"$name/Initialize") { val helperInitialize = helper.initialize() (helperInitialize._1, helperInitialize._2, initialCellState) } } /** This method specifies what happens in each step of decoding. * * @return Tuple containing: (i) the decoder output, (ii) the next state, (iii) the next inputs, and (iv) a scalar * tensor specifying whether sampling has finished. */ override def next( time: Output[Int], input: Out, state: State ): (BasicDecoder.BasicDecoderOutput[Out, Sample], State, Out, Output[Boolean]) = { tf.nameScope(s"$name/Next") { val nextTuple = cell(tf.RNNTuple(input, state)) val nextTupleOutput = outputLayer(nextTuple.output) val sample = helper.sample(time, nextTupleOutput, nextTuple.state) val (finished, nextInputs, nextState) = helper.next(time, nextTupleOutput, nextTuple.state, sample) (BasicDecoder.BasicDecoderOutput(nextTupleOutput, sample), nextState, nextInputs, finished) } } /** Finalizes the output of the decoding process. * * @param output Final output after decoding. * @param state Final state after decoding. * @return Finalized output and state to return from the decoding process. */ override def finalize( output: BasicDecoder.BasicDecoderOutput[Out, Sample], state: State, sequenceLengths: Output[Int] ): (BasicDecoder.BasicDecoderOutput[Out, Sample], State, Output[Int]) = { (output, state, sequenceLengths) } } object BasicDecoder { def apply[Out: OutputStructure, State: OutputStructure, Sample: OutputStructure, OutShape, StateShape, SampleShape]( cell: tf.RNNCell[Out, State, OutShape, StateShape], initialCellState: State, helper: BasicDecoder.Helper[Out, Sample, State], outputLayer: Out => Out = (o: Out) => o, name: String = "BasicRNNDecoder" )(implicit evOutputToShapeOut: OutputToShape.Aux[Out, OutShape], evOutputToShapeState: OutputToShape.Aux[State, StateShape], evOutputToShapeSample: OutputToShape.Aux[Sample, SampleShape], evZeroOut: Zero.Aux[Out, OutShape], evZeroSample: Zero.Aux[Sample, SampleShape] ): BasicDecoder[Out, State, Sample, OutShape, StateShape, SampleShape] = { new BasicDecoder(cell, initialCellState, helper, outputLayer, name) } case class BasicDecoderOutput[Out, Sample](modelOutput: Out, sample: Sample) /** Interface for implementing sampling helpers in sequence-to-sequence decoders. */ trait Helper[Out, Sample, State] { /** Scalar tensor representing the batch size of a tensor returned by `sample()`. */ val batchSize: Output[Int] /** Returns a zero-valued sample for this helper. */ def zeroSample( batchSize: Output[Int], name: String = "ZeroSample" ): Sample /** Returns a tuple containing: (i) a scalar tensor specifying whether initialization has finished, and * (ii) the next input. */ def initialize(): (Output[Boolean], Out) /** Returns a sample for the provided time, input, and state. */ def sample( time: Output[Int], input: Out, state: State ): Sample /** Returns a tuple containing: (i) a scalar tensor specifying whether sampling has finished, and * (ii) the next inputs, and (iii) the next state. */ def next( time: Output[Int], input: Out, state: State, sample: Sample ): (Output[Boolean], Out, State) } /** RNN decoder helper to be used while training. It only reads inputs and the returned sample indexes are the argmax * over the RNN output logits. */ case class TrainingHelper[Out, State, OutShape]( input: Out, sequenceLengths: Output[Int], timeMajor: Boolean = false, name: String = "RNNDecoderTrainingHelper" )(implicit evOutputStructure: OutputStructure[Out], evOutputToShapeOut: OutputToShape.Aux[Out, OutShape], evZeroOut: Zero.Aux[Out, OutShape] ) extends Helper[Out, Out, State] { if (sequenceLengths.rank != 1) throw InvalidShapeException(s"'sequenceLengths' (shape = ${sequenceLengths.shape}) must have rank 1.") private var inputs: Seq[Output[Any]] = { OutputStructure[Out].outputs(input) } private val inputTensorArrays: Seq[TensorArray[Any]] = { tf.nameScope(name) { if (!timeMajor) { // [B, T, D] => [T, B, D] inputs = inputs.map(i => { RNN.transposeBatchTime(i)(TF.fromDataType(i.dataType)) }) } inputs.map(input => { TensorArray.create( size = tf.shape(input)(TF.fromDataType(input.dataType)).castTo[Int].slice(0), elementShape = input.shape(1 ::) )(TF.fromDataType(input.dataType)).unstack(input) }) } } private val zeroInputs: Seq[Output[Any]] = { tf.nameScope(name) { inputs.map(input => { tf.zerosLike( tf.gather( input = input, indices = 0 )(TF.fromDataType(input.dataType), TF[Int], IsIntOrLong[Int], IntDefault[Int], TF[Int], IsIntOrLong[Int])) }) } } /** Scalar tensor representing the batch size of a tensor returned by `sample()`. */ override val batchSize: Output[Int] = { tf.nameScope(name) { tf.size(sequenceLengths).castTo[Int] } } /** Returns a zero-valued sample for this helper. */ def zeroSample( batchSize: Output[Int], name: String = "ZeroSample" ): Out = { val shapes = evOutputStructure.outputs(input).map(_ => Shape.scalar()) val shape = evOutputToShapeOut.decodeShape(input, shapes)._1 evZeroOut.zero(batchSize, shape) } /** Returns a tuple containing: (i) a scalar tensor specifying whether initialization has finished, and * (ii) the next input. */ override def initialize(): (Output[Boolean], Out) = { tf.nameScope(s"$name/Initialize") { val finished = tf.equal(0, sequenceLengths) val nextInputs = tf.cond( tf.all(finished), () => zeroInputs, () => inputTensorArrays.map(_.read(0))) (finished, OutputStructure[Out].decodeOutput(input, nextInputs)._1) } } /** Returns a sample for the provided time, input, and state. */ override def sample( time: Output[Int], input: Out, state: State ): Out = { val outputs = evOutputStructure.outputs(input) tf.nameScope(s"$name/Sample") { OutputStructure[Out].decodeOutput(input, outputs.map(output => { // TODO: [TYPES] !!! Super hacky. Remove in the future. val ev: IsNotQuantized[Any] = null tf.argmax( output, axes = -1, outputDataType = Int )(TF.fromDataType(output.dataType), ev, TF[Int], IsIntOrLong[Int], TF[Int]) }))._1 } } /** Returns a tuple containing: (i) a scalar tensor specifying whether sampling has finished, and * (ii) the next inputs, and (iii) the next state. */ override def next( time: Output[Int], input: Out, state: State, sample: Out ): (Output[Boolean], Out, State) = { tf.nameScope(s"$name/NextInputs") { val nextTime = time + 1 val finished = tf.greaterEqual(nextTime, sequenceLengths) val nextInputs = tf.cond( tf.all(finished), () => zeroInputs, () => inputTensorArrays.map(_.read(nextTime))) (finished, evOutputStructure.decodeOutput(input, nextInputs)._1, state) } } } /** RNN decoder helper to be used while performing inference. It uses the argmax over the RNN output logits and passes * the result through an embedding layer to get the next input. * * @param embeddingFn Function that takes an vector of IDs and returns the corresponding embedded values * that will be passed to the decoder input. * @param beginTokens Vector with length equal to the batch size, which contains the begin-of-sequence token IDs. * @param endToken Scalar containing the end-of-sequence token ID (i.e., token ID which marks the end of * decoding). */ case class GreedyEmbeddingHelper[T, State]( embeddingFn: Output[Int] => Output[T], beginTokens: Output[Int], endToken: Output[Int], name: String = "RNNDecoderGreedyEmbeddingHelper" ) extends Helper[Output[T], Output[Int], State] { if (beginTokens.rank != 1) throw InvalidShapeException(s"'beginTokens' (shape = ${beginTokens.shape}) must have rank 1.") if (endToken.rank != 0) throw InvalidShapeException(s"'endToken' (shape = ${endToken.shape}) must have rank 0.") private val beginInputs: Output[T] = { tf.nameScope(name) { embeddingFn(beginTokens) } } /** Scalar tensor representing the batch size of a tensor returned by `sample()`. */ override val batchSize: Output[Int] = { tf.nameScope(name) { tf.size(beginTokens).castTo[Int] } } /** Returns a zero-valued sample for this helper. */ def zeroSample( batchSize: Output[Int], name: String = "ZeroSample" ): Output[Int] = { tf.nameScope(name) { tf.fill[Int, Int](batchSize.expandDims(0))(0) } } /** Returns a tuple containing: (i) a scalar tensor specifying whether initialization has finished, and * (ii) the next input. */ override def initialize(): (Output[Boolean], Output[T]) = { tf.nameScope(s"$name/Initialize") { (tf.tile(Tensor(false), batchSize.expandDims(0)), beginInputs) } } /** Returns a sample for the provided time, input, and state. */ override def sample( time: Output[Int], input: Output[T], state: State ): Output[Int] = { tf.nameScope(s"$name/Sample") { // TODO: [TYPES] !!! Super hacky. Remove in the future. implicit val ev: IsNotQuantized[T] = null implicit val evTF: TF[T] = TF.fromDataType(input.dataType) tf.argmax(input, axes = -1, outputDataType = endToken.dataType) } } /** Returns a tuple containing: (i) a scalar tensor specifying whether sampling has finished, and * (ii) the next RNN cell tuple. */ override def next( time: Output[Int], input: Output[T], state: State, sample: Output[Int] ): (Output[Boolean], Output[T], State) = { tf.nameScope(s"$name/NextInputs") { val finished = tf.equal(sample, endToken) val nextInputs = tf.cond( tf.all(finished), // If we are finished, the next inputs value does not matter. () => beginInputs, () => embeddingFn(sample)) (finished, nextInputs, state) } } } }
15,861
37.877451
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/decoders/Decoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.decoders import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.core.exception.InvalidShapeException import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape, Zero} import org.platanios.tensorflow.api.ops.rnn.RNN import scala.language.postfixOps /** Represents Recurrent Neural Network (RNN) decoders. * * Concepts used by this interface: * * - `input`: (structure of) tensors and tensor arrays that is passed as input to the RNN cell composing the * decoder, at each time step. * - `state`: Sequence of tensors that is passed to the RNN cell instance as the state. * - `finished`: Boolean tensor indicating whether each sequence in the batch has finished decoding. * * @param cell RNN cell to use for decoding. * @param name Name prefix used for all created ops. * * @author Emmanouil Antonios Platanios */ abstract class Decoder[ Out, State, DecOut: OutputStructure, DecState: OutputStructure, DecFinalOut: OutputStructure, DecFinalState, OutShape, StateShape, DecOutShape, DecStateShape ]( val cell: tf.RNNCell[Out, State, OutShape, StateShape], val name: String = "RNNDecoder" )(implicit evOutputToShapeOut: OutputToShape.Aux[Out, OutShape], evOutputToShapeState: OutputToShape.Aux[State, StateShape], evOutputToShapeDecState: OutputToShape.Aux[DecState, DecStateShape], evZeroOut: Zero.Aux[Out, OutShape], evZeroDecOut: Zero.Aux[DecOut, DecOutShape] ) { /** Scalar tensor representing the batch size of the input values. */ val batchSize: Output[Int] /** Describes whether the decoder keeps track of finished states. * * Most decoders will emit a true/false `finished` value independently at each time step. In this case, the * `decode()` function keeps track of which batch entries have already finished, and performs a logical OR to * insert new batches to the finished set. * * Some decoders, however, shuffle batches/beams between time steps and `decode()` will mix up the finished * states across these entries because it does not track the reshuffling across time steps. In this case, it is up to * the decoder to declare that it will keep track of its own finished state by setting this property to `true`. */ val tracksOwnFinished: Boolean = false /** Returns a zero-valued output for this decoder. */ def zeroOutput: DecOut /** Returns the shape invariants for this decoder loop. * * @return Tuple containing: (i) the shape invariant for the "finished" signal, (ii) the decoder input shape * invariant, (iii) the decoder output shape invariant, and (iv) the decoder state shape invariant. */ def shapeInvariants: (Shape, OutShape, DecOutShape, DecStateShape) /** This method is called before any decoding iterations. It computes the initial input values and the initial state. * * @return Tuple containing: (i) a scalar tensor specifying whether initialization has finished, * (ii) the next input, and (iii) the initial decoder state. */ def initialize(): (Output[Boolean], Out, DecState) /** This method specifies what happens in each step of decoding. * * @return Tuple containing: (i) the decoder output for this step, (ii) the next decoder state, (iii) the next input, * and (iv) a scalar tensor specifying whether decoding has finished. */ def next( time: Output[Int], input: Out, state: DecState ): (DecOut, DecState, Out, Output[Boolean]) /** Finalizes the output of the decoding process. * * @param output Final output after decoding. * @param state Final state after decoding. * @param sequenceLengths Tensor containing the sequence lengths that the decoder cell outputs. * @return Finalized output and state to return from the decoding process. */ def finalize( output: DecOut, state: DecState, sequenceLengths: Output[Int] ): (DecFinalOut, DecFinalState, Output[Int]) /** Performs dynamic decoding using this decoder. * * This method calls `initialize()` once and `next()` repeatedly. */ def decode( outputTimeMajor: Boolean = false, imputeFinished: Boolean = false, maximumIterations: Output[Int] = null, parallelIterations: Int = 32, swapMemory: Boolean = false, name: String = s"$name/DynamicRNNDecode" ): (DecFinalOut, DecFinalState, Output[Int]) = { val evStructureDecOut = OutputStructure[DecOut] val evStructureDecState = OutputStructure[DecState] val evStructureDecFinalOut = OutputStructure[DecFinalOut] if (maximumIterations != null && maximumIterations.rank != 0) { throw InvalidShapeException( s"'maximumIterations' (shape = ${maximumIterations.shape}) must be a scalar.") } // Create a new variable scope in which the caching device is either determined by the parent scope, or is set to // place the cached variables using the same device placement as for the rest of the RNN. val currentVariableScope = tf.VariableScope.current val cachingDevice = { if (currentVariableScope.cachingDevice == null) (opSpecification: tf.OpSpecification) => opSpecification.device else currentVariableScope.cachingDevice } tf.updatedVariableScope(currentVariableScope, cachingDevice = cachingDevice) { tf.nameScope(name) { var (initialFinished, initialInput, initialState) = initialize() val zeroOutput = this.zeroOutput val zeroOutputs = evStructureDecOut.outputs(zeroOutput) val initialOutputTensorArrays = zeroOutputs.map(output => { TensorArray.create( size = 0, dynamicSize = true, elementShape = output.shape )(TF.fromDataType(output.dataType)) }) if (maximumIterations != null) initialFinished = tf.logicalOr(initialFinished, tf.greaterEqual(0, maximumIterations)) val initialSequenceLengths = tf.zerosLike(initialFinished).castTo[Int] val initialTime = tf.zeros[Int](Shape.scalar()) type LoopVariables = ( Output[Int], Seq[TensorArray[Any]], DecState, Out, Output[Boolean], Output[Int]) def condition(loopVariables: LoopVariables): Output[Boolean] = { tf.logicalNot(tf.all(loopVariables._5)) } def body(loopVariables: LoopVariables): LoopVariables = { val (time, outputTensorArrays, state, input, finished, sequenceLengths) = loopVariables val (decoderOutput, decoderState, nextInput, decoderFinished) = next(time, input, state) val decoderOutputs = evStructureDecOut.outputs(decoderOutput) val decoderStates = evStructureDecState.outputs(decoderState) var nextFinished = { if (tracksOwnFinished) decoderFinished else tf.logicalOr(decoderFinished, finished) } if (maximumIterations != null) nextFinished = tf.logicalOr(nextFinished, tf.greaterEqual(time + 1, maximumIterations)) val nextSequenceLengths = tf.select( tf.logicalAnd(tf.logicalNot(finished), nextFinished), tf.fill[Int, Int](tf.shape(sequenceLengths))(time + 1), sequenceLengths) // Zero out output values past finish and pass through state when appropriate val (nextOutputs, nextStates) = { if (imputeFinished) { val nextOutputs = decoderOutputs.zip(zeroOutputs).map(o => { tf.select(finished, o._2, o._1)(TF.fromDataType(o._2.dataType)) }) // Passes `decoderStates` through as the next state depending on their corresponding value in `finished` // and on their type and shape. Tensor arrays and scalar states are always passed through. val states = evStructureDecState.outputs(state) val nextStates = decoderStates.zip(states).map(s => { s._1.setShape(s._2.shape) if (s._1.rank == 0) { s._1 } else { tf.select(finished, s._2, s._1)(TF.fromDataType(s._2.dataType)) } }) (nextOutputs, nextStates) } else { (decoderOutputs, decoderStates) } } val nextState = evStructureDecState.decodeOutput(state, nextStates)._1 val nextOutputTensorArrays = outputTensorArrays.zip(nextOutputs).map(t => { t._1.write(time, t._2) }) (time + 1, nextOutputTensorArrays, nextState, nextInput, nextFinished, nextSequenceLengths) } val (finishedShapeInvariant, inputShapeInvariant, outputShapeInvariant, stateShapeInvariant) = shapeInvariants val (_, finalOutputTensorArrays, preFinalState, _, _, preFinalSequenceLengths): LoopVariables = tf.whileLoop( (loopVariables: LoopVariables) => condition(loopVariables), (loopVariables: LoopVariables) => body(loopVariables), (initialTime, initialOutputTensorArrays, initialState, initialInput, initialFinished, initialSequenceLengths), shapeInvariants = Some(( Shape(), evZeroDecOut.evOutputToShape.shapeStructure.shapes(outputShapeInvariant).map(_ => Shape()), stateShapeInvariant, inputShapeInvariant, finishedShapeInvariant, Shape(-1, -1))), parallelIterations = parallelIterations, swapMemory = swapMemory) var (finalOutput, finalState, finalSequenceLengths) = finalize( evStructureDecOut.decodeOutput(zeroOutput, finalOutputTensorArrays.map(_.stack()))._1, preFinalState, preFinalSequenceLengths) if (!outputTimeMajor) { finalOutput = evStructureDecFinalOut.decodeOutput( finalOutput, evStructureDecFinalOut.outputs(finalOutput).map(o => { RNN.transposeBatchTime(o)(TF.fromDataType(o.dataType)) }))._1 } (finalOutput, finalState, finalSequenceLengths) } } } }
10,968
43.408907
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/decoders/BeamSearchDecoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.decoders import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.core.exception.{InvalidArgumentException, InvalidShapeException} import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToShape, Zero} import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import scala.collection.mutable.ArrayBuffer import scala.language.postfixOps // TODO: [SEQ2SEQ] Abstract away the log-softmax/scoring function. /** Recurrent Neural Network (RNN) that uses beam search to find the highest scoring sequence (i.e., perform decoding). * * @param cell RNN cell to use for decoding. * @param initialCellState Initial RNN cell state to use for starting the decoding process. * @param embeddingFn Function that takes an vector of IDs and returns the corresponding embedded * values that will be passed to the decoder input. * @param beginTokens Vector with length equal to the batch size, which contains the begin-of-sequence * token IDs. * @param endToken Scalar containing the end-of-sequence token ID (i.e., token ID which marks the end of * decoding). * @param beamWidth Beam width to use for the beam search while decoding. * @param lengthPenalty Length penalty method. * @param outputLayer Output layer to use that is applied at the outputs of the provided RNN cell before * returning them. * @param reorderTensorArrays If `true`, `TensorArray`s' elements within the cell state will be reordered according to * the beam search path. If the `TensorArray` can be reordered, the stacked form will be * returned. Otherwise, the `TensorArray` will be returned as is. Set this flag to `false` * if the cell state contains any `TensorArray`s that are not amenable to reordering. * @param name Name prefix used for all created ops. * * @author Emmanouil Antonios Platanios */ class BeamSearchDecoder[T: TF, State: OutputStructure, StateShape]( override val cell: tf.RNNCell[Output[T], State, Shape, StateShape], val initialCellState: State, val embeddingFn: Output[Int] => Output[T], val beginTokens: Output[Int], val endToken: Output[Int], val beamWidth: Int, val lengthPenalty: LengthPenalty = NoLengthPenalty, val outputLayer: Output[T] => Output[T] = (o: Output[T]) => o, val reorderTensorArrays: Boolean = true, override val name: String = "BeamSearchRNNDecoder" )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape] ) extends Decoder[ /* Out */ Output[T], /* State */ State, /* DecOut */ BeamSearchDecoder.BeamSearchDecoderOutput, /* DecState */ BeamSearchDecoder.BeamSearchDecoderState[State], /* DecFinalOut */ BeamSearchDecoder.BeamSearchFinalOutput, /* DecFinalState */ BeamSearchDecoder.BeamSearchDecoderState[State], /* Shapes */ Shape, StateShape, (Shape, Shape, Shape), (StateShape, Shape, Shape, Shape) ](cell, name) { if (beginTokens.rank != 1) throw InvalidShapeException(s"'beginTokens' (shape = ${beginTokens.shape}) must have rank 1.") if (endToken.rank != 0) throw InvalidShapeException(s"'endToken' (shape = ${endToken.shape}) must have rank 0.") /** Scalar tensor representing the batch size of the input values. */ override val batchSize: Output[Int] = { tf.nameScope(name) { tf.size(beginTokens).castTo[Int] } } private val beginInput: Output[T] = { tf.nameScope(name) { val tiledBeginTokens = tf.tile(tf.expandDims(beginTokens, 1), tf.stack[Int](Seq(1, beamWidth))) embeddingFn(tiledBeginTokens) } } /** Describes whether the decoder keeps track of finished states. * * Most decoders will emit a true/false `finished` value independently at each time step. In this case, the * `dynamicDecode()` function keeps track of which batch entries have already finished, and performs a logical OR to * insert new batches to the finished set. * * Some decoders, however, shuffle batches/beams between time steps and `dynamicDecode()` will mix up the finished * state across these entries because it does not track the reshuffling across time steps. In this case, it is up to * the decoder to declare that it will keep track of its own finished state by setting this property to `true`. * * The beam-search decoder shuffles its beams and their finished state. For this reason, it conflicts with the * `dynamicDecode` function's tracking of finished states. Setting this property to `true` avoids early stopping of * decoding due to mismanagement of the finished state in `dynamicDecode`. */ override val tracksOwnFinished: Boolean = { true } /** Returns a zero-valued output for this decoder. */ override def zeroOutput: BeamSearchDecoder.BeamSearchDecoderOutput = { // We assume the data type of the cell is the same as the initial cell state's first component tensor data type. val zScores = Zero[Output[Float]].zero(batchSize, Shape(beamWidth), "ZeroScores") val zPredictedIDs = Zero[Output[Int]].zero(batchSize, Shape(beamWidth), "ZeroPredictedIDs") val zParentIDs = Zero[Output[Int]].zero(batchSize, Shape(beamWidth), "ZeroParentIDs") BeamSearchDecoder.BeamSearchDecoderOutput(zScores, zPredictedIDs, zParentIDs) } /** Returns the shape invariants for this decoder loop. * * @return Tuple containing: (i) the shape invariant for the "finished" signal, (ii) the decoder input shape * invariant, (iii) the decoder output shape invariant, and (iv) the decoder state shape invariant. */ override def shapeInvariants: (Shape, Shape, (Shape, Shape, Shape), (StateShape, Shape, Shape, Shape)) = { def _shapeConverter(shape: Shape): Shape = { val newShape = Array.fill[Int](shape.rank + 1)(-1) newShape(0) = shape(0) newShape(1) = beamWidth if (shape.rank > 1) newShape(newShape.length - 1) = shape(shape.rank - 1) Shape(newShape) } val cellStateShapeInvariant = evOutputToShapeState.shapeStructure.map( evOutputToShapeState.shape(initialCellState), _shapeConverter) (Shape(-1, beamWidth), Shape(-1, beamWidth, beginInput.shape(2)), (Shape(-1, beamWidth), Shape(-1, beamWidth), Shape(-1, beamWidth)), (cellStateShapeInvariant, Shape(-1, beamWidth), Shape(-1, beamWidth), Shape(-1, beamWidth))) } /** This method is called before any decoding iterations. It computes the initial input values and the initial state. * * @return Tuple containing: (i) a scalar tensor specifying whether initialization has finished, * (ii) the next input, and (iii) the initial decoder state. */ override def initialize(): (Output[Boolean], Output[T], BeamSearchDecoder.BeamSearchDecoderState[State]) = { tf.nameScope(s"$name/Initialize") { val tiledInitialCellState = { val evStructureState = OutputStructure[State] if (evStructureState.outputs(initialCellState).exists(_.rank == -1)) throw InvalidArgumentException("All tensors in the state need to have known rank for the beam search decoder.") evStructureState.map(initialCellState, new OutputStructure.Converter { @throws[InvalidArgumentException] override def apply[V](value: Output[V], shape: Option[Shape]): Output[V] = { implicit val evTF: TF[V] = TF.fromDataType(value.dataType) if (value.rank == -1) { throw InvalidArgumentException("The provided tensor must have statically known rank.") } else if (value.rank == 0) { val tiling = Tensor(beamWidth) val tiled = tf.tile(value.expandDims(0), tiling) tiled.setShape(Shape(beamWidth)) tiled } else { val tiling = ArrayBuffer.fill(value.rank + 1)(1) tiling(1) = beamWidth tf.tile(value.expandDims(1), tiling) } } }) } val finished = tf.oneHot[Boolean, Int]( indices = tf.zeros[Int, Int](batchSize.expandDims(0)), depth = beamWidth, onValue = false, offValue = true) val initialState = BeamSearchDecoder.BeamSearchDecoderState[State]( modelState = tiledInitialCellState, logProbabilities = tf.oneHot[Float, Int]( indices = tf.zeros[Int](batchSize.expandDims(0)), depth = beamWidth, onValue = tf.zeros[Float](Shape()), offValue = tf.constant(Float.MinValue)), finished = finished, sequenceLengths = tf.zeros[Int](tf.stack[Int](Seq(batchSize, beamWidth)))) (finished, beginInput, initialState) } } /** This method specifies what happens in each step of decoding. * * @return Tuple containing: (i) the decoder output, (ii) the next state, (iii) the next inputs, and (iv) a scalar * tensor specifying whether sampling has finished. */ override def next( time: Output[Int], input: Output[T], state: BeamSearchDecoder.BeamSearchDecoderState[State] ): (BeamSearchDecoder.BeamSearchDecoderOutput, BeamSearchDecoder.BeamSearchDecoderState[State], Output[T], Output[Boolean]) = { val evStructureState = OutputStructure[State] tf.nameScope(s"$name/Next") { val mergedInput = BeamSearchDecoder.MergeBatchBeamsConverter(batchSize, beamWidth)(input, Some(input.shape(2 ::))) val mergedCellState = evOutputToShapeState.map( state.modelState, Some(cell.stateShape), BeamSearchDecoder.MaybeTensorConverter( BeamSearchDecoder.MergeBatchBeamsConverter(batchSize, beamWidth))) val mergedNextTuple = cell(tf.RNNTuple(mergedInput, mergedCellState)) val nextTupleOutput = outputLayer(BeamSearchDecoder.SplitBatchBeamsConverter(batchSize, beamWidth)( mergedNextTuple.output, Some(mergedNextTuple.output.shape(1 ::)))) val nextTupleState = evOutputToShapeState.map( mergedNextTuple.state, Some(cell.stateShape), BeamSearchDecoder.MaybeTensorConverter( BeamSearchDecoder.SplitBatchBeamsConverter(batchSize, beamWidth))) // Perform the beam search step. val staticBatchSize = Output.constantValue(batchSize).map(_.scalar).getOrElse(-1) // Calculate the current lengths of the predictions. val predictionLengths = state.sequenceLengths val previouslyFinished = state.finished // Calculate the total log probabilities for the new hypotheses (final shape = [batchSize, beamWidth, vocabSize]). val expandedStateLogProbabilities = tf.expandDims( state.logProbabilities, axis = 2, name = "LogProbabilities/ExpandDims") val stepLogProbabilities = BeamSearchDecoder.maskLogProbabilities( tf.logSoftmax(nextTupleOutput.toFloat), endToken, previouslyFinished) val totalLogProbabilities = expandedStateLogProbabilities + stepLogProbabilities // Calculate the continuation lengths by adding to all continuing search states. val vocabSize = { if (nextTupleOutput.shape(-1) != -1) tf.constant(nextTupleOutput.shape(-1)) else tf.shape(nextTupleOutput).toInt.slice(-1) } val lengthsToAdd = tf.oneHot[Int, Int]( indices = tf.fill[Int, Int](tf.stack[Int](Seq(batchSize, beamWidth)))(endToken), depth = vocabSize, onValue = 0, offValue = 1) val addMask = tf.logicalNot(previouslyFinished).toInt val newPredictionLengths = tf.add( lengthsToAdd * tf.expandDims(addMask, axis = 2, name = "AddMask/ExpandDims"), tf.expandDims(predictionLengths, axis = 2, name = "PredictionLengths/ExpandDims")) // Calculate the scores for each search state. val scores = lengthPenalty(totalLogProbabilities, newPredictionLengths).toFloat // During the first time step we only consider the initial search state. val scoresFlat = tf.reshape(scores, tf.stack[Int](Seq(batchSize, -1))) // Pick the next search states according to the specified successors function. val nextBeamSize = tf.constant(beamWidth, name = "BeamWidth") val (nextBeamScores, wordIndices) = tf.topK(scoresFlat, nextBeamSize) nextBeamScores.setShape(Shape(staticBatchSize, beamWidth)) wordIndices.setShape(Shape(staticBatchSize, beamWidth)) // Pick out the log probabilities, search state indices, and states according to the chosen predictions. val nextBeamLogProbabilities = BeamSearchDecoder.gather( gatherIndices = wordIndices, gatherFrom = totalLogProbabilities, batchSize = batchSize, rangeSize = vocabSize * beamWidth, gatherShape = Seq(-1), name = "NextBeamLogProbabilities") val nextPredictedIDs = tf.mod(wordIndices, vocabSize, name = "NextBeamPredictedIDs").toInt val nextParentIDs = tf.divide(wordIndices, vocabSize, name = "NextBeamParentIDs").toInt // Append the new IDs to the current predictions. val gatheredFinished = BeamSearchDecoder.gather( gatherIndices = nextParentIDs, gatherFrom = previouslyFinished, batchSize = batchSize, rangeSize = beamWidth, gatherShape = Seq(-1), name = "NextBeamFinishedGather") val nextFinished = tf.logicalOr( gatheredFinished, tf.equal(nextPredictedIDs, endToken), name = "NextBeamFinished") // Calculate the length of the next predictions: // 1. Finished search states remain unchanged. // 2. Search states that just finished (i.e., `endToken` predicted) have their length increased by 1. // 3. Search states that have not yet finished have their length increased by 1. val nextPredictionLengths = BeamSearchDecoder.gather( gatherIndices = nextParentIDs, gatherFrom = state.sequenceLengths, batchSize = batchSize, rangeSize = beamWidth, gatherShape = Seq(-1), name = "NextBeamLengthsGather" ) + tf.logicalNot(gatheredFinished).toInt // Pick out the cell state according to the next search state parent IDs. We use a different gather shape here // because the cell state tensors (i.e., the tensors that would be gathered from) all have rank greater than two // and we need to preserve those dimensions. val gatheredNextTupleState = evStructureState.map( nextTupleState, BeamSearchDecoder.MaybeTensorConverter( new OutputStructure.Converter { override def apply[V](value: Output[V], shape: Option[Shape]): Output[V] = { implicit val evVTF: TF[V] = TF.fromDataType(value.dataType) val valueShape = tf.shape(value) val gatherShape = (batchSize * beamWidth) +: (2 until value.rank).map(valueShape(_)) BeamSearchDecoder.gather( nextParentIDs, value, batchSize, beamWidth, gatherShape, name = "NextBeamStateGather") } })) val nextState = BeamSearchDecoder.BeamSearchDecoderState[State]( gatheredNextTupleState, nextBeamLogProbabilities, nextPredictionLengths, nextFinished) val output = BeamSearchDecoder.BeamSearchDecoderOutput(nextBeamScores, nextPredictedIDs, nextParentIDs) val nextInput = tf.cond( nextFinished.all(), () => beginInput, () => embeddingFn(nextPredictedIDs)) (output, nextState, nextInput, nextFinished) } } /** Finalizes the output of the decoding process. * * @param output Final output after decoding. * @param state Final state after decoding. * @return Finalized output and state to return from the decoding process. */ override def finalize( output: BeamSearchDecoder.BeamSearchDecoderOutput, state: BeamSearchDecoder.BeamSearchDecoderState[State], sequenceLengths: Output[Int] ): (BeamSearchDecoder.BeamSearchFinalOutput, BeamSearchDecoder.BeamSearchDecoderState[State], Output[Int]) = { // Get the maximum sequence length across all search states for each batch val maxSequenceLengths = state.sequenceLengths.max(Tensor[Int](1)) val predictedIDs = BeamSearchDecoder.gatherTree( output.predictedIDs, output.parentIDs, maxSequenceLengths, endToken) val finalOutput = BeamSearchDecoder.BeamSearchFinalOutput(predictedIDs, output) var finalState = state if (reorderTensorArrays) finalState = state.copy[State](modelState = OutputStructure[State].map( state.modelState, BeamSearchDecoder.MaybeSortTensorArrayBeamsConverter( state.sequenceLengths, output.parentIDs, batchSize, beamWidth))) (finalOutput, finalState, finalState.sequenceLengths) } } object BeamSearchDecoder { protected[BeamSearchDecoder] val logger = Logger(LoggerFactory.getLogger("Ops / Beam Search Decoder")) def apply[T: TF, State: OutputStructure, StateShape]( cell: tf.RNNCell[Output[T], State, Shape, StateShape], initialCellState: State, embeddingFn: Output[Int] => Output[T], beginTokens: Output[Int], endToken: Output[Int], beamWidth: Int, lengthPenalty: LengthPenalty = NoLengthPenalty, outputLayer: Output[T] => Output[T] = (o: Output[T]) => o, reorderTensorArrays: Boolean = true, name: String = "BeamSearchRNNDecoder" )(implicit evOutputToShapeState: OutputToShape.Aux[State, StateShape] ): BeamSearchDecoder[T, State, StateShape] = { new BeamSearchDecoder[T, State, StateShape]( cell, initialCellState, embeddingFn, beginTokens, endToken, beamWidth, lengthPenalty, outputLayer, reorderTensorArrays, name) } case class BeamSearchDecoderOutput( scores: Output[Float], predictedIDs: Output[Int], parentIDs: Output[Int]) case class BeamSearchDecoderState[State]( modelState: State, logProbabilities: Output[Float], sequenceLengths: Output[Int], finished: Output[Boolean]) /** Final outputs returned by the beam search after all decoding is finished. * * @param predictedIDs Tensor of shape `[batchSize, T, beamWidth]` (or `[T, batchSize, beamWidth]`, * if `outputTimeMajor == true`) containing the final prediction IDs. The search states are * ordered from best to worst. * @param output State of the beam search at the end of decoding. */ case class BeamSearchFinalOutput( predictedIDs: Output[Int], output: BeamSearchDecoderOutput) /** Masks log probabilities. The result is that finished search states allocate all probability mass to `endToken` and * unfinished search states remain unchanged. * * @param logProbabilities Log probability for each hypothesis, which is a tensor with shape * `[batchSize, beamWidth, vocabSize]`. * @param endToken Scalar tensor containing the end-of-sequence token ID. * @param finished Tensor of shape `[batchSize, beamWidth]` that specifies which elements in the beam have * finished decoding. * @return Tensor of shape `[batchSize, beamWidth, vocabSize]`, where unfinished search states stay unchanged and * finished search states are replaced with a tensor with all probability mass allocated to `endToken`. */ private[BeamSearchDecoder] def maskLogProbabilities( logProbabilities: Output[Float], endToken: Output[Int], finished: Output[Boolean] ): Output[Float] = { val vocabSize = tf.shape(logProbabilities).castTo[Int].slice(2) // Finished examples are replaced with a vector that has all its probability mass on `endToken` val finishedRow = tf.oneHot[Float, Int]( indices = endToken, depth = vocabSize, onValue = tf.zeros[Float](Shape()), offValue = tf.constant(Float.MinValue)) val finishedLogProbabilities = tf.tile( input = finishedRow.reshape(Shape(1, 1, -1)), multiples = tf.concatenate[Int](Seq(tf.shape(finished).castTo[Int], Tensor(1)), 0)) val finishedMask = tf.tile( input = tf.expandDims(finished, axis = 2, name = "Finished/ExpandDims"), multiples = tf.stack[Int](Seq(1, 1, vocabSize))) tf.select(finishedMask, finishedLogProbabilities, logProbabilities) } /** The `gatherTree` op calculates the full search states from the per-step IDs and parent beam IDs. * * On a CPU, if an out-of-bounds parent ID is found, an error is returned. On a GPU, if an out-of-bounds parent ID * is found, a `-1` is stored in the corresponding output value and the execution for that beam returns early. * * For a given beam, past the time step containing the first decoded `endToken`, all values are filled in with * `endToken`. * * @param stepIDs Tensor with shape `[maxTime, batchSize, beamWidth]`, containing the step IDs. * @param parentIDs Tensor with shape `[maxTime, batchSize, beamWidth]`, containing the parent IDs. * @param maxSequenceLengths Tensor with shape `[batchSize]`, containing the sequence lengths. * @param endToken Scalar tensor containing the end-of-sequence token ID. * @param name Name for the created op. * @return Created op output. */ private[decoders] def gatherTree( stepIDs: Output[Int], parentIDs: Output[Int], maxSequenceLengths: Output[Int], endToken: Output[Int], name: String = "GatherTree" ): Output[Int] = { Op.Builder[(Output[Int], Output[Int], Output[Int], Output[Int]), Output[Int]]( opType = "GatherTree", name = name, input = (stepIDs, parentIDs, maxSequenceLengths, endToken) ).build().output } /** Maybe converts the provided tensor. */ private[BeamSearchDecoder] case class MaybeTensorConverter( innerConverter: OutputStructure.Converter ) extends OutputStructure.Converter { @throws[InvalidArgumentException] override def apply[T](value: Output[T], shape: Option[Shape]): Output[T] = { if (value.rank == -1) { throw InvalidArgumentException(s"Expected tensor ($value) to have known rank, but it was unknown.") } else if (value.rank == 0) { value } else { innerConverter(value, shape) } } @throws[InvalidArgumentException] override def apply[T](value: tf.data.Dataset[T], shape: Option[Shape]): tf.data.Dataset[T] = { throw InvalidArgumentException("Unsupported argument type for use with the beam search decoder.") } } /** Converts the provided tensor structure from batches by beams into batches of beams, by merging them accordingly. * * More precisely, `value` consists of tensors with shape `[batchSize * beamWidth] ++ ...` and this method reshapes * them into tensors with shape `[batchSize, beamWidth] ++ ...`. * * @throws InvalidArgumentException If `value` is of an unsupported type. * @throws InvalidShapeException If the provided value contains any tensors of unknown rank, or if, after * reshaping, the new tensor is not shaped `[batchSize, beamWidth] ++ ...` * (assuming that both `batchSize` and `beamWidth` are known statically). */ private[BeamSearchDecoder] case class SplitBatchBeamsConverter( batchSize: Output[Int], beamWidth: Int ) extends OutputStructure.Converter { @throws[InvalidArgumentException] @throws[InvalidShapeException] override def apply[T](value: Output[T], shape: Option[Shape]): Output[T] = { implicit val evTTF: TF[T] = TF.fromDataType(value.dataType) val valueShape = tf.shape(value) val reshapedValue = tf.reshape(value, tf.concatenate(Seq( batchSize.expandDims(0), Output[Int](beamWidth), valueShape(1 ::)), axis = 0)) val staticBatchSize = Output.constantValue(batchSize).map(_.scalar).getOrElse(-1) val expectedReshapedShape = Shape(staticBatchSize, beamWidth) ++ shape.get if (!reshapedValue.shape.isCompatibleWith(expectedReshapedShape)) { throw InvalidShapeException( "Unexpected behavior when reshaping between beam width and batch size. " + s"The reshaped tensor has shape: ${reshapedValue.shape}. " + s"We expected it to have shape [batchSize, beamWidth, depth] == $expectedReshapedShape. " + "Perhaps you forgot to create a zero state with batchSize = encoderBatchSize * beamWidth?") } reshapedValue.setShape(expectedReshapedShape) reshapedValue } @throws[InvalidArgumentException] override def apply[T](value: tf.data.Dataset[T], shape: Option[Shape]): tf.data.Dataset[T] = { throw InvalidArgumentException("Unsupported argument type for use with the beam search decoder.") } } /** Converts the provided tensor structure from a batch of search states into a batch by beams, by merging them * accordingly> * * More precisely, `value` consists of tensors with shape `[batchSize, beamWidth] ++ ...` and this method reshapes * them into tensors with shape `[batchSize * beamWidth] ++ ...`. * * @throws InvalidArgumentException If `value` is of an unsupported type. * @throws InvalidShapeException If the provided value contains any tensors of unknown rank, or if, after * reshaping, the new tensor is not shaped `[batchSize * beamWidth] ++ ...` * (assuming that both `batchSize` and `beamWidth` are known statically). */ private[BeamSearchDecoder] case class MergeBatchBeamsConverter( batchSize: Output[Int], beamWidth: Int ) extends OutputStructure.Converter { @throws[InvalidArgumentException] @throws[InvalidShapeException] override def apply[T](value: Output[T], shape: Option[Shape]): Output[T] = { implicit val evTTF: TF[T] = TF.fromDataType(value.dataType) val valueShape = tf.shape(value) val reshapedValue = tf.reshape(value, tf.concatenate(Seq( batchSize.expandDims(0) * Output[Int](beamWidth), valueShape(2 ::)), axis = 0)) val staticBatchSize = Output.constantValue(batchSize).map(_.scalar).getOrElse(-1) val batchSizeBeamWidth = if (staticBatchSize != -1) staticBatchSize * beamWidth else -1 val expectedReshapedShape = Shape(batchSizeBeamWidth) ++ shape.get if (!reshapedValue.shape.isCompatibleWith(expectedReshapedShape)) { throw InvalidShapeException( "Unexpected behavior when reshaping between beam width and batch size. " + s"The reshaped tensor has shape: ${reshapedValue.shape}. " + s"We expected it to have shape [batchSize, beamWidth, depth] == $expectedReshapedShape. " + "Perhaps you forgot to create a zero state with batchSize = encoderBatchSize * beamWidth?") } reshapedValue.setShape(expectedReshapedShape) reshapedValue } @throws[InvalidArgumentException] override def apply[T](value: tf.data.Dataset[T], shape: Option[Shape]): tf.data.Dataset[T] = { throw InvalidArgumentException("Unsupported argument type for use with the beam search decoder.") } } /** Gathers the right indices from the provided `gatherFrom` value. This works by reshaping all tensors in * `gatherFrom` to `gatherShape` (e.g., `Seq(-1)`) and then gathering from that according to the `gatherIndices`, * which are offset by the right amount in order to preserve the batch order. * * @param gatherIndices Indices that we use to gather from `gatherFrom`. * @param gatherFrom Value to gather from. * @param batchSize Input batch size. * @param rangeSize Number of values in each range. Likely equal to the beam width. * @param gatherShape What we should reshape `gatherFrom` to in order to preserve the correct values. An example * is when `gatherFrom` is the attention from an `AttentionWrapperState` with shape * `[batchSize, beamWidth, attentionSize]`. There, we want to preserve the `attentionSize` * elements, and so `gatherShape` is set to `Seq(batchSize * beamWidth, -1)`. Then, upon * reshape, we still have the `attentionSize` elements, as desired. * @return Value containing the gathered tensors of shapes `tf.shape(gatherFrom)(0 :: 1 + gatherShape.size())`. * @throws InvalidArgumentException If `gatherFrom` is of an unsupported type. */ @throws[InvalidArgumentException] private[BeamSearchDecoder] def gather[T]( gatherIndices: Output[Int], gatherFrom: Output[T], batchSize: Output[Int], rangeSize: Output[Int], gatherShape: Seq[Output[Int]], name: String = "GatherTensorHelper" ): Output[T] = { implicit val evTTF: TF[T] = TF.fromDataType(gatherFrom.dataType) tf.nameScope(name) { val range = (tf.range(0, batchSize) * rangeSize).expandDims(1) val reshapedGatherIndices = (gatherIndices + range).reshape(Shape(-1)) val output = tf.gather(gatherFrom.reshape(tf.stack(gatherShape)), reshapedGatherIndices, axis = 0) val finalShape = tf.shape(gatherFrom).slice(0 :: (1 + gatherShape.size)) tf.reshape(output, finalShape, name = "Output") } } /** Checks are known statically and can be reshaped to `[batchSize, beamSize, -1]` and logs a warning * if they cannot. */ private[BeamSearchDecoder] def checkStaticBatchBeam( shape: Shape, batchSize: Int, beamWidth: Int ): Boolean = { if (batchSize != -1 && shape(0) != -1 && (shape(0) != batchSize * beamWidth || (shape.rank > 1 && shape(1) != -1 && (shape(0) != batchSize || shape(1) != beamWidth)))) { val reshapedShape = Shape(batchSize, beamWidth, -1) logger.warn( s"Tensor array reordering expects elements to be reshapable to '$reshapedShape' which is incompatible with " + s"the current shape '$shape'. Consider setting `reorderTensorArrays` to `false` to disable tensor array " + "reordering during the beam search.") false } else { true } } /** Returns an assertion op checking that the elements of the stacked tensor array (i.e., `tensor`) can be reshaped * to `[batchSize, beamSize, -1]`. At this point, the tensor array elements have a known rank of at least `1`. */ private[BeamSearchDecoder] def checkBatchBeam[T]( tensor: Output[T], batchSize: Output[Int], beamWidth: Output[Int] ): UntypedOp = { implicit val evTF: TF[T] = TF.fromDataType(tensor.dataType) tf.assert( condition = { val shape = tf.shape(tensor).castTo[Int] if (tensor.rank == 2) tf.equal(shape(1), batchSize * beamWidth) else tf.logicalOr( tf.equal(shape(1), batchSize * beamWidth), tf.logicalAnd( tf.equal(shape(1), batchSize), tf.equal(shape(2), beamWidth))) }, data = Seq(Tensor( "Tensor array reordering expects elements to be reshapable to '[batchSize, beamSize, -1]' which is " + s"incompatible with the dynamic shape of '${tensor.name}' elements. Consider setting " + "`reorderTensorArrays` to `false` to disable tensor array reordering during the beam search." ).toOutput)) } /** Maybe sorts the search states within a tensor array. The input tensor array corresponds to the symbol to be * sorted. This will only be sorted if it is a tensor array of size `maxTime` that contains tensors with shape * `[batchSize, beamWidth, s]` or `[batchSize * beamWidth, s]`, where `s` is the depth shape. * * The converter returns a tensor array where the search states are sorted in each tensor, or `value` itself, if it * is not a tensor array or does not meet the shape requirements. * * @param sequenceLengths Tensor containing the sequence lengths, with shape `[batchSize, beamWidth]`. * @param parentIDs Tensor containing the parent indices, with shape `[maxTime, batchSize, beamWidth]`. * @param batchSize Batch size. * @param beamWidth Beam width. */ case class MaybeSortTensorArrayBeamsConverter( sequenceLengths: Output[Int], parentIDs: Output[Int], batchSize: Output[Int], beamWidth: Int ) extends OutputStructure.Converter { override def apply[T](value: TensorArray[T], shape: Option[Shape]): TensorArray[T] = { if ((!value.inferShape || value.elementShape.isEmpty) || value.elementShape.get(0) == -1 || value.elementShape.get(1) < 1 ) { implicit val evTTF: TF[T] = TF.fromDataType(value.dataType) val shape = value.elementShape match { case Some(s) if value.inferShape => Shape(s(0)) case _ => Shape(-1) } logger.warn( s"The tensor array '${value.handle.name}' in the cell state is not amenable to sorting based on the beam " + s"search result. For a tensor array to be sorted, its elements shape must be defined and have at least " + s"a rank of 1. However, the elements shape in the provided tensor array is: $shape.") value } else if (!checkStaticBatchBeam( shape = Shape(value.elementShape.get(0)), batchSize = Output.constantValue(batchSize).map(_.scalar).getOrElse(-1), beamWidth = beamWidth) ) { value } else { implicit val evTTF: TF[T] = TF.fromDataType(value.dataType) val stackedTensorArray = value.stack() tf.createWith(controlDependencies = Set(checkBatchBeam(stackedTensorArray, batchSize, beamWidth))) { val maxTime = tf.shape(parentIDs).castTo[Int].slice(0) val batchSize = tf.shape(parentIDs).castTo[Int].slice(1) val beamWidth = tf.shape(parentIDs).castTo[Int].slice(2) // Generate search state indices that will be reordered by the `gatherTree` op. val searchStateIndices = tf.tile( tf.range(0, beamWidth).slice(NewAxis, NewAxis), tf.stack[Int](Seq(maxTime, batchSize, 1))) val mask = tf.sequenceMask(sequenceLengths, maxTime).castTo[Int].transpose(Seq(2, 0, 1)) // Use `beamWidth + 1` to mark the end of the beam. val maskedSearchStateIndices = (searchStateIndices * mask) + (1 - mask) * (beamWidth + 1) val maxSequenceLengths = sequenceLengths.max(Tensor[Int](1)).castTo[Int] var sortedSearchStateIndices = gatherTree( maskedSearchStateIndices, parentIDs, maxSequenceLengths, beamWidth + 1) // For out of range steps, we simply copy the same beam. sortedSearchStateIndices = tf.select(mask.toBoolean, sortedSearchStateIndices, searchStateIndices) // Generate indices for `gatherND`. val timeIndices = tf.tile( tf.range(0, maxTime).slice(NewAxis, NewAxis), tf.stack[Int](Seq(1, batchSize, beamWidth))) val batchIndices = tf.tile( tf.range(0, batchSize).slice(NewAxis, NewAxis), tf.stack[Int](Seq(1, maxTime, beamWidth))).transpose(Seq(1, 0, 2)) val indices = tf.stack(Seq(timeIndices, batchIndices, sortedSearchStateIndices), -1) // Gather from a tensor with collapsed additional dimensions. val finalShape = tf.shape(stackedTensorArray) val gatherFrom = stackedTensorArray.reshape(tf.stack[Int](Seq(maxTime, batchSize, beamWidth, -1))) // TODO: [TYPES] !!! This cast is wrong. I need to figure out the right behavior for this. tf.gatherND(gatherFrom, indices).reshape(finalShape).asInstanceOf[TensorArray[T]] } } } @throws[InvalidArgumentException] override def apply[T](value: tf.data.Dataset[T], shape: Option[Shape]): tf.data.Dataset[T] = { throw InvalidArgumentException("Unsupported argument type for use with the beam search decoder.") } } }
37,057
49.625683
129
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/decoders/BeamSearchDecoder2.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ // package org.platanios.symphony.mt.models.helpers.decoders // import org.platanios.tensorflow.api._ // import org.platanios.tensorflow.api.core.Indexer.NewAxis // import org.platanios.tensorflow.api.core.exception.{InvalidArgumentException, InvalidShapeException} // import org.platanios.tensorflow.api.implicits.Implicits._ // import org.platanios.tensorflow.api.implicits.helpers.OutputStructure // import scala.collection.mutable.ArrayBuffer // import scala.language.postfixOps // /** // * @author Emmanouil Antonios Platanios // */ // object BeamSearchDecoder2 { // /** Merges the first two dimensions of `value` into one. // * // * Typically, the first dimension corresponds to the batch size and the second to the beam width. So, for example, // * if `value` has shape `[batchSize, beamWidth, ...]`, the resulting tensor will have shape // * `[batchSize * beamWidth, ...]`. // * // * @param value Tensor to reshape. // * @return `value` reshaped such that its first two dimensions are merged into one. // */ // private[BeamSearchDecoder2] def mergeBeams[T: TF]( // value: Output[T] // ): Output[T] = { // val valueShape = Basic.shape(value) // val batchSize = valueShape(0) // val beamWidth = valueShape(1) // val mergedSize = batchSize * beamWidth // val mergedShape = Basic.concatenate(Seq(mergedSize(NewAxis), valueShape(2 ::)), axis = 0) // Basic.reshape(value, mergedShape) // } // /** Splits the first dimension of `value` into two, reversing the merge operation of `mergeBeams`. // * // * For example, if `value` has shape `[batchSize * beamWidth, ...]`, the resulting tensor will have shape // * `[batchSize, beamWidth, ...]`. // * // * @param value Tensor to reshape. // * @param batchSize Original batch size. // * @param beamWidth Original beam width. // * @return `value` reshaped such that its first dimension are split into two. // */ // private[BeamSearchDecoder2] def splitBeams[T: TF]( // value: Output[T], // batchSize: Output[Int], // beamWidth: Output[Int] // ): Output[T] = { // val valueShape = Basic.shape(value) // val splitShape = Basic.concatenate(Seq(batchSize(NewAxis), beamWidth(NewAxis), valueShape(1 ::)), axis = 0) // Basic.reshape(value, splitShape) // } // /** Adds a new dimension to `value` and tiles it along that dimension, `beamWidth` times. // * // * If `value` is a scalar, then a vector is returned, otherwise, the new beam dimension is always introduced as the // * second dimension. For example, if `value` has shape `[batchSize, ...]`, then the resulting tensor will have shape // * `[batchSize, beamWidth]`. // * // * @param value Tensor to tile. // * @param beamWidth Beam width (i.e., number of times to tile value). // * @return `value` tiled and reshaped so that it now has a beam dimension. // * @throws InvalidArgumentException If the rank of `value` is unknown. // */ // @throws[InvalidArgumentException] // private[BeamSearchDecoder2] def tileForBeamSearch[T: TF]( // value: Output[T], // beamWidth: Int // ): Output[T] = { // if (value.rank == -1) { // throw InvalidArgumentException("The provided tensor must have statically known rank.") // } else if (value.rank == 0) { // Basic.tile(value.expandDims(0), multiples = Tensor(beamWidth)) // } else { // val multiples = ArrayBuffer.fill(value.rank + 1)(1) // multiples(1) = beamWidth // Basic.tile(value.expandDims(1), multiples) // } // } // /** Returns the shape of `value`, but with all its inner dimensions replaced with `-1`. // * // * @param value Tensor whose shape invariants to return. // * @return `value` shape with all its inner dimensions replaced with `-1`. // */ // private[BeamSearchDecoder2] def getStateShapeInvariants( // value: Output[_] // ): Shape = { // Shape.fromSeq(value.shape.asArray.zipWithIndex.map(s => { // if (s._2 == 0 || s._2 == value.rank - 1) // s._1 // else // -1 // })) // } // /** Beam search decoder state. // * // * @param sequences Tensor of sequences we need to gather from, with shape `[batchSize, beamWidth, length]`. // * @param scores Tensor of scores for each sequence in `sequences`, with shape `[batchSize, beamWidth]`. // * @param finished Tensor of boolean flags indicating whether each sequence in `sequences` has finished // * (i.e. has reached end-of-sequence), with shape `[batchSize, beamWidth]`. // * @param decodingState Decoding state. // */ // case class BeamSearchState[T: TF : IsReal, S: OutputStructure]( // sequences: Output[T], // scores: Output[Float], // finished: Output[Boolean], // decodingState: Option[S]) // /** Given a beam search decoder state, this method will gather the top `beamWidth` sequences, scores, etc., and // * return a new, updated beam search decoder state. // * // * This method permits easy introspection using the TensorFlow debugger. It add named ops, prefixed by `name` and // * with names `TopKSequences`, `TopKFinished`, and `TopKScores`.. // * // * @param state Beam search state. // * @param scoresToGather Tensor of scores to gather, for each sequence in `sequences`, with shape // * `[batchSize, beamWidth]`. These scores may differ from `scores` because for `growAlive`, // * we need to return log probabilities, while for `growFinished`, we need to return length // * penalized scores. // * @param beamWidth Integer specifying the beam width. // * @param useTPU Boolean flag indicating whether the created ops will be executed on TPUs. // * @param name Name scope to use for the created ops. // */ // private[BeamSearchDecoder2] def computeTopKScoresAndSequences[T: TF : IsReal, S: OutputStructure]( // state: BeamSearchState[T, S], // scoresToGather: Output[Float], // beamWidth: Int, // useTPU: Boolean = false, // name: String = "ComputeTopKScoresAndSequences" // ): BeamSearchState[T, S] = { // Op.nameScope(name) { // val batchSize = Basic.shape(state.sequences).slice(0) // if (useTPU) { // val topKIndices = computeTopKUnique(state.scores, k=beamWidth)._2 // // Gather up the highest scoring sequences. We give each operation added a concrete name to simplify observing // // these operations with the TensorFlow debugger. Clients can capture these tensors by watching these node names. // val topKSequences = tpuGather(state.sequences, topKIndices, name = "TopKSequences") // val topKFinished = tpuGather(state.finished, topKIndices, name = "TopKFinished") // val topKScores = tpuGather(scoresToGather, topKIndices, name = "TopKScores") // val topKStates = state.decodingState.map(s => { // OutputStructure[S].map(s, new OutputStructure.Converter { // override def apply[T](value: Output[T], shape: Option[Shape]): Output[T] = { // tpuGather(value, topKIndices, name = "TopKStates") // } // }) // }) // BeamSearchState(topKSequences, topKScores, topKFinished, topKStates) // } else { // val topKIndices = NN.topK(state.scores, k = beamWidth) // // The next steps are used to create indices for `gatherND` to pull out the top `k` sequences from // // sequences based on scores. The batch indices tensor looks like `[ [0, 0, 0, ...], [1, 1, 1, ...], ... ]`, // // and it indicates which batch each beam item is in. This will create the `i` of the `[i, j]` coordinate // // needed for a gather. // val batchIndices = computeBatchIndices(batchSize, beamWidth) // // The top indices specify which indices to use for the gather. The result of the stacking operation is a tensor // // with shape `[batchSize, beamWidth, 2]`, where the last dimension specifies the gather indices. // val topIndices = Basic.stack(Seq(batchIndices, topKIndices), axis = 2) // // Next, we gather the highest scoring sequences. We give each operation added a concrete name to simplify // // observing these operations with the TensorFlow debugger. Clients can capture these tensors by watching these // // node names. // val topKSequences = Basic.gatherND(state.sequences, topIndices, name = "TopKSequences") // val topKFinished = Basic.gatherND(state.finished, topIndices, name = "TopKFinished") // val topKScores = Basic.gatherND(scoresToGather, topIndices, name = "TopKScores") // val topKStates = state.decodingState.map(s => { // OutputStructure[S].map(s, new OutputStructure.Converter { // override def apply[T](value: Output[T], shape: Option[Shape]): Output[T] = { // Basic.gatherND(value, topIndices, name = "TopKStates") // } // }) // }) // BeamSearchState(topKSequences, topKScores, topKFinished, topKStates) // } // } // } // /** Computes the `i`th coordinate that contains the batch index for gathers. // * // * The batch indices tensor looks like `[ [0, 0, 0, ...], [1, 1, 1, ...], ... ]`, and it indicates which batch each // * beam item is in. This will create the `i` of the `[i, j]` coordinate needed for a gather. // * // * @param batchSize Batch size. // * @param beamWidth Beam width. // * @return Tensor with shape `[batchSize, beamWidth]`, containing batch indices. // */ // private[BeamSearchDecoder2] def computeBatchIndices( // batchSize: Output[Int], // beamWidth: Output[Int] // ): Output[Int] = { // val batchIndices = Math.truncateDivide(Math.range(0, batchSize * beamWidth), beamWidth) // Basic.reshape(batchIndices, Seq(batchSize, beamWidth)) // } // /** Finds the values and indices of the `k` largest entries in `input`. // * // * Instead of performing a sort like the `topK` op, this method finds the maximum value `k` times. The running time // * is proportional to `k`, which is going to be faster for small values of `k`. The current implementation only // * supports inputs of rank 2. In addition, iota is used to replace the lower bits of each element, which makes the // * selection more stable when there are equal elements. The overhead is that output values are approximate. // * // * @param input Input tensor with shape `[batchSize, depth]`. // * @param k Number of top elements to select. // * @return Tuple containing: // * - Tensor with shape `[batchSize, k]`, which contains the top `k` elements in `input`. // * - Tensor with shape `[batchSize, k]`, which contains the indices of the top `k` elements in `input`. // */ // private[BeamSearchDecoder2] def computeTopKUnique[T: TF]( // input: Output[T], // k: Int // ): (Output[T], Output[Int]) = { // val uniqueInput = makeUnique(input.toFloat) // val height = uniqueInput.shape(0) // val width = uniqueInput.shape(1) // val negInfR0 = Basic.constant[Float](Float.NegativeInfinity) // val negInfR2 = Basic.fill(Shape(height, width))(negInfR0) // val infFilteredInput = Math.select(Math.isNaN(uniqueInput), negInfR2, uniqueInput) // // Select the current largest value `k` times and keep the selected values in `topKR2`. // // The selected largest values are marked as the smallest values to avoid being selected again. // var temp = uniqueInput // var topKR2 = Basic.zeros[Float](Shape(height, k)) // for (i <- 0 until k) { // val kthOrderStatistics = Math.max(temp, axes = 1, keepDims = true) // val kMask = Basic.tile( // input = Math.equal[Int](Math.range[Int](0, k), Basic.fill(Shape(k))(Basic.constant[Int](i))).expandDims(0), // multiples = Tensor[Int](height, 1)) // topKR2 = Math.select(kMask, Basic.tile(kthOrderStatistic, Tensor[Int](1, k)), topKR2) // temp = Math.select( // condition = Math.greaterEqual(uniqueInput, Basic.tile(kthOrderStatistic, Tensor[Int](1, width))), // x = negInfR2, // y = uniqueInput) // } // val log2Ceil = scala.math.ceil(scala.math.log(width) / scala.math.log(2)).toInt // val nextPowerOfTwo = 1 << log2Ceil // val countMask = nextPowerOfTwo - 1 // TODO: Why is this not the same as the one in `makeUnique`. // val countMaskR0 = Basic.constant(countMask) // val countMaskR2 = Basic.fill(Shape(height, k))(countMaskR0) // val topKR2Int = topKR2.bitcastTo[Int] // val topKIndicesR2 = Math.bitwise.and(topKR2Int, countMaskR2) // (topKR2.castTo[T], topKIndicesR2) // } // /** Replaces the lower bits of each element with iota. // * // * The iota is used to derive the index, and also serves the purpose of making each element unique to break ties. // * // * @param input Input tensor with rank 2. // * @return Resulting tensor after an element-wise transformation on `input`. // * @throws InvalidShapeException If the rank of `input` is not equal to 2. // */ // @throws[InvalidShapeException] // private[BeamSearchDecoder2] def makeUnique( // input: Output[Float] // ): Output[Float] = { // if (input.rank != 2) // throw InvalidShapeException(s"Expected rank-2 input, but got input with shape ${input.shape}.") // val height = input.shape(0) // val width = input.shape(1) // // The count mask is used to mask away the low order bits thus ensuring that every element is distinct. // val log2Ceil = scala.math.ceil(scala.math.log(width) / scala.math.log(2)).toInt // val nextPowerOfTwo = 1 << log2Ceil // val countMask = ~(nextPowerOfTwo - 1) // val countMaskR0 = Basic.constant(countMask) // val countMaskR2 = Basic.fill(Shape(height, width))(countMaskR0) // // This is the bit representation of the smallest positive normal floating point number. The sign is zero, the // // exponent is one, and the fraction is zero. // val smallestNormal = 1 << 23 // val smallestNormalR0 = Basic.constant(smallestNormal) // val smallestNormalR2 = Basic.fill(Shape(height, width))(smallestNormalR0) // // This is used to mask away the sign bit when computing the absolute value. // val lowBitMask = ~(1 << 31) // val lowBitMaskR0 = Basic.constant(lowBitMask) // val lowBitMaskR2 = Basic.fill(Shape(height, width))(lowBitMaskR0) // // Compare the absolute value with positive zero to handle negative zero. // val inputR2 = input.bitcastTo[Int] // val absR2 = Math.bitwise.and(inputR2, lowBitMaskR2) // val inputNoZerosR2 = Math.select( // condition = Math.equal(absR2, 0), // x = Math.bitwise.or(inputR2, smallestNormalR2), // y = inputR2) // val iota = Basic.tile( // input = Math.range[Int](0, width).expandDims(0), // multiples = Tensor(height, 1)) // // Discard the low-order bits and replace with iota. // val andR2 = Math.bitwise.and(inputNoZerosR2, countMaskR2) // val orR2 = Math.bitwise.or(andR2, iota) // orR2.bitcastTo[Float] // } // /** Fast gather implementation for models running on TPUs. // * // * This function uses a one-hot tensor and a batch matrix multiplications to perform the gather, which is faster // * than `gatherND` on TPUs. For integer inputs, (i.e., tensors to gather from), `batchGather` is used instead, in // * order to maintain reasonable accuracy. // * // * @param input Tensor from which to gather values, with shape `[batchSize, ...]`. // * @param indices Indices to use for the gather, which is a tensor with shape `[batchSize, numIndices]`. // * @param name Namescope for the created ops. // * @return Tensor that contains the gathered values and has the same rank as `input`, and shape // * `[batchSize, numIndices, ...]`. // */ // private[BeamSearchDecoder2] def tpuGather[T: TF : IsNotQuantized, I: TF : IsIntOrLong]( // input: Output[T], // indices: Output[I], // name: String = "Gather" // ): Output[T] = { // Op.nameScope(name) { // // If the data type is `INT32`, use the gather instead of the ont-hot matrix multiplication, in order to avoid // // precision loss. The maximum integer value that can be represented by `BFLOAT16` in the MXU is 256, which is // // smaller than the possible `indices` values. Encoding/decoding can potentially be used to make it work, but // // the benefit is small right now. // if (input.dataType == INT32) { // Basic.batchGather(input, indices) // } else if (input.dataType != FLOAT32) { // val floatResult = tpuGather(input.toFloat, indices) // floatResult.castTo[T] // } else { // val inputShape = Basic.shape(input) // val inputRank = input.rank // // Adjust the shape of the input to match one-hot indices, // // which is a requirement for batch matrix multiplication. // val reshapedInput = inputRank match { // case 2 => Basic.expandDims(input, axis = -1) // case r if r > 3 => Basic.reshape(input, Seq(inputShape(0), inputShape(1), Basic.constant[Int](-1))) // case _ => input // } // val oneHot = Basic.oneHot[T, I](indices, depth = inputShape(1).toInt) // val gatherResult = Math.matmul(oneHot, reshapedInput) // inputRank match { // case 2 => Basic.squeeze(gatherResult, axes = Seq(-1)) // case r if r > 3 => // val resultShape = Basic.concatenate(Seq( // inputShape(0).expandDims(0), // Basic.shape(indices).slice(1).expandDims(0), // inputShape(2 ::) // ), axis = 0) // Basic.reshape(gatherResult, resultShape) // case _ => gatherResult // } // } // } // } // }
18,923
49.464
124
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/pivoting/Pivot.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.pivoting import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.models.parameters.ParameterManager import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ trait Pivot { def initialize( languages: Seq[(Language, Vocabulary)], parameterManager: ParameterManager ): Unit def pivotingSequence( srcLanguage: Output[Int], tgtLanguage: Output[Int] ): Output[Int] }
1,177
30.837838
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/pivoting/SinglePivot.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.pivoting import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.models.parameters.ParameterManager import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ case class SinglePivot( pivotLanguage: Language, supportedPairs: Set[(Language, Language)] ) extends Pivot { protected var pivotLanguageId : Output[Int] = _ protected var supportedLanguagePairIds: Seq[(Output[Int], Output[Int])] = _ override def initialize( languages: Seq[(Language, Vocabulary)], parameterManager: ParameterManager ): Unit = { pivotLanguageId = parameterManager.languageId(languages.map(_._1).indexOf(pivotLanguage)) supportedLanguagePairIds = supportedPairs.toSeq.map { case (src, tgt) => (parameterManager.languageId(languages.map(_._1).indexOf(src)), parameterManager.languageId(languages.map(_._1).indexOf(tgt))) } } override def pivotingSequence( srcLanguage: Output[Int], tgtLanguage: Output[Int] ): Output[Int] = { tf.cases( predicateFnPairs = supportedLanguagePairIds.map(lp => (tf.logicalAnd(tf.equal(lp._1, srcLanguage), tf.equal(lp._2, tgtLanguage)), () => tgtLanguage(NewAxis))), default = () => tf.stack(Seq(pivotLanguageId, tgtLanguage))) } }
2,056
36.4
113
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/pivoting/NoPivot.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.pivoting import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.models.parameters.ParameterManager import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ object NoPivot extends Pivot { override def initialize( languages: Seq[(Language, Vocabulary)], parameterManager: ParameterManager ): Unit = { () } override def pivotingSequence( srcLanguage: Output[Int], tgtLanguage: Output[Int] ): Output[Int] = { tgtLanguage(NewAxis) } }
1,260
29.756098
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/hooks/TrainingLogger.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.hooks import org.platanios.symphony.mt.models.{Sentences, SentencesWithLanguage, SentencesWithLanguagePair} import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.implicits.helpers.{OutputStructure, OutputToTensor} import org.platanios.tensorflow.api.learn.Counter import org.platanios.tensorflow.api.learn.hooks._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import java.nio.file.Path /** Hooks that logs the training speed, the perplexity value, and the gradient norm while training. * * @param trigger Hook trigger specifying when this hook is triggered (i.e., when it executes). If you only want * to log the tensor values at the end of a run and not during, then you should set `trigger` to * [[NoHookTrigger]] and `logAtEnd` to `true`. * @param triggerAtEnd If `true`, this hook will be triggered at the end of the run. Note that if this flag is set to * `true`, then `tensors` must be computable without using a feed map for the `Session.run()` * call. * @param formatter Function used to format the message that is being logged. It takes the time taken since the * last logged message, the current step, the current gradients norm, the current perplexity * value, as input, and returns a string to log. * * @author Emmanouil Antonios Platanios */ case class TrainingLogger( log: Boolean = true, summaryDir: Path = null, trigger: HookTrigger = StepHookTrigger(1), triggerAtEnd: Boolean = true, average: Boolean = true, dataParallelFactor: Float = 1.0f, formatter: (Option[Double], Long, Float, Float, Option[Double]) => String = null, summaryTag: String = "Training" ) extends ModelDependentHook[ /* In */ SentencesWithLanguagePair[String], /* TrainIn */ (SentencesWithLanguagePair[String], Sentences[String]), /* Out */ SentencesWithLanguage[String], /* TrainOut */ SentencesWithLanguage[Float], /* Loss */ Float, /* EvalIn */ (SentencesWithLanguage[String], (SentencesWithLanguagePair[String], Sentences[String]))] with SummaryWriterHookAddOn { require(log || summaryDir != null, "At least one of 'log' and 'summaryDir' needs to be provided.") private var step : Output[Long] = _ private var gradientsNorm: Output[Float] = _ private var loss : Output[Float] = _ private var batchSize : Output[Long] = _ private var srcWordCount : Output[Long] = _ private var tgtWordCount : Output[Long] = _ private val internalTrigger : HookTrigger = trigger.copy() private var lastStep : Long = 0L private var shouldTrigger : Boolean = false private var totalGradientsNorm: Float = 0.0f private var totalLoss : Float = 0.0f private var totalNumSamples : Long = 0L private var totalSrcWordCount : Long = 0L private var totalTgtWordCount : Long = 0L override protected def begin(): Unit = { step = Counter.get(Graph.Keys.GLOBAL_STEP, local = false).getOrElse(throw new IllegalStateException( s"A ${Graph.Keys.GLOBAL_STEP.name} variable should be created in order to use the 'TrainingLogger'.") ).value internalTrigger.reset() shouldTrigger = false gradientsNorm = modelInstance.gradientsAndVariables.map(g => tf.globalNorm(g.map(_._1))).orNull loss = modelInstance.loss.map(_.toFloat).flatMap(l => { modelInstance.trainInput.map(o => l * /* batch size */ tf.size(o._2._2).toFloat) }).orNull batchSize = modelInstance.trainInput.map(o => tf.size(o._2._2)).orNull srcWordCount = modelInstance.trainInput.map(o => { /* source sentence lengths */ tf.sum(o._1._3._2).toLong }).orNull tgtWordCount = modelInstance.trainInput.map(o => { /* target sentence lengths */ tf.sum(o._2._2).toLong + /* batch size */ tf.size(o._2._2) }).orNull totalLoss = 0.0f totalNumSamples = 0L totalSrcWordCount = 0L totalTgtWordCount = 0L } override protected def afterSessionCreation(session: Session): Unit = { lastStep = session.run(fetches = step).scalar } override protected def beforeSessionRun[C: OutputStructure, CV]( runContext: Hook.SessionRunContext[C, CV] )(implicit evOutputToTensorC: OutputToTensor.Aux[C, CV] ): Option[Hook.SessionRunArgs[Seq[Output[Any]], Seq[Tensor[Any]]]] = { shouldTrigger = gradientsNorm != null && loss != null && internalTrigger.shouldTriggerForStep(lastStep.toInt + 1) if (average || shouldTrigger) { Some(Hook.SessionRunArgs(fetches = Seq[Output[Any]]( step, gradientsNorm, loss, batchSize, srcWordCount, tgtWordCount))) } else { Some(Hook.SessionRunArgs(fetches = Seq[Output[Any]](step))) } } override protected def afterSessionRun[C: OutputStructure, CV]( runContext: Hook.SessionRunContext[C, CV], runResult: Hook.SessionRunResult[Seq[Tensor[Any]]] )(implicit evOutputToTensorC: OutputToTensor.Aux[C, CV] ): Unit = { processFetches(runResult.result) } override protected def end(session: Session): Unit = { if (triggerAtEnd && lastStep.toInt != internalTrigger.lastTriggerStep().getOrElse(-1)) { shouldTrigger = true processFetches(session.run(fetches = Seq[Output[Any]]( step, gradientsNorm, loss, batchSize, srcWordCount, tgtWordCount))) } } private def processFetches(fetches: Seq[Tensor[Any]]): Unit = { lastStep = fetches.head.scalar.asInstanceOf[Long] if (average || shouldTrigger) { totalGradientsNorm += fetches(1).scalar.asInstanceOf[Float] totalLoss += fetches(2).scalar.asInstanceOf[Float] totalNumSamples += fetches(3).scalar.asInstanceOf[Long] totalSrcWordCount += fetches(4).scalar.asInstanceOf[Long].toInt totalTgtWordCount += fetches(5).scalar.asInstanceOf[Long].toInt if (shouldTrigger) { val numSteps = (lastStep * dataParallelFactor).toInt val elapsed = internalTrigger.updateLastTrigger(lastStep.toInt) val elapsedTime = elapsed.map(_._1) val totalWordCount = (totalSrcWordCount + totalTgtWordCount) * dataParallelFactor val avgPerplexity = Math.exp(totalLoss * dataParallelFactor / totalNumSamples).toFloat val avgGradientsNorm = totalGradientsNorm / elapsed.map(_._2).getOrElse(1) val avgSrcSentenceLength = totalSrcWordCount * dataParallelFactor / totalNumSamples val avgTgtSentenceLength = totalTgtWordCount * dataParallelFactor / totalNumSamples val message = { if (formatter != null) { formatter( elapsedTime, numSteps, avgGradientsNorm, avgPerplexity, elapsedTime.map(s => totalWordCount / (1000 * s))) } else { elapsedTime match { case Some(s) => val wps = totalWordCount / (1000 * s) f"($s%9.3f s / $wps%6.2fk words/s ) " + f"Step: $numSteps%6d, " + f"Perplexity: $avgPerplexity%12.4f, " + f"GradNorm: $avgGradientsNorm%12.4f, " + f"AvgSrcSenLen: $avgSrcSentenceLength%6.2f, " + f"AvgTgtSenLen: $avgTgtSentenceLength%6.2f" case None => f"( timing not available yet ) " + f"Step: $numSteps%6d, " + f"Perplexity: $avgPerplexity%12.4f, " + f"GradNorm: $avgGradientsNorm%12.4f, " + f"AvgSrcSenLen: $avgSrcSentenceLength%6.2f, " + f"AvgTgtSenLen: $avgTgtSentenceLength%6.2f" } } } if (log) TrainingLogger.logger.info(message) writeSummary(lastStep, s"$summaryTag/Perplexity", avgPerplexity) writeSummary(lastStep, s"$summaryTag/GradientsNorm", avgGradientsNorm) writeSummary(lastStep, s"$summaryTag/AverageSourceSentenceLength", avgSrcSentenceLength) writeSummary(lastStep, s"$summaryTag/AverageTargetSentenceLength", avgTgtSentenceLength) totalGradientsNorm = 0.0f totalLoss = 0.0f totalNumSamples = 0L totalSrcWordCount = 0L totalTgtWordCount = 0L } } } } object TrainingLogger { private[TrainingLogger] val logger = Logger(LoggerFactory.getLogger("Learn / Hooks / Training Logger")) }
9,142
45.411168
119
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/curriculum/DifficultyBasedCurriculum.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.curriculum import org.platanios.symphony.mt.data.scores.{SentenceScore, SentenceScoreHistogram} import org.platanios.symphony.mt.models.curriculum.competency.Competency import org.platanios.tensorflow.api._ // TODO: Things to consider: // - Length discrepancy // - Word frequency // - Alignment /** * @author Emmanouil Antonios Platanios */ abstract class DifficultyBasedCurriculum[Sample]( val competency: Competency[Output[Float]], val score: SentenceScore, val maxNumHistogramBins: Int = 1000 ) extends Curriculum[Sample] { private[models] val cdfScore: SentenceScore = { SentenceScoreHistogram(score, maxNumHistogramBins).cdfScore } override final def samplesFilter: Option[Sample => Output[Boolean]] = { Some((sample: Sample) => tf.nameScope("Curriculum/SamplesFilter") { tf.lessEqual(sampleScore(sample), competency.currentLevel(getCurrentStep.value)) }) } protected def sampleScore(sample: Sample): Output[Float] }
1,654
34.212766
86
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/curriculum/Curriculum.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.curriculum import org.platanios.symphony.mt.models.Context import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ trait Curriculum[Sample] { private var currentStep: Variable[Long] = _ def initialize()(implicit context: Context): Unit = () protected def getCurrentStep: Variable[Long] = { if (currentStep == null) { tf.device("/CPU:0") { currentStep = tf.variable[Long]("Curriculum/Step", Shape(), tf.ZerosInitializer, trainable = false) } } currentStep } def updateState(step: Output[Long]): UntypedOp = { getCurrentStep.assign(step).op } def samplesFilter: Option[Sample => Output[Boolean]] = { None } def >>(other: Curriculum[Sample]): Curriculum[Sample] = { compose(other) } def compose(other: Curriculum[Sample]): Curriculum[Sample] = { new Curriculum[Sample] { override def samplesFilter: Option[Sample => Output[Boolean]] = { (samplesFilter, other.samplesFilter) match { case (Some(thisFilter), Some(otherFilter)) => Some((sample: Sample) => { tf.cond( thisFilter(sample), () => otherFilter(sample), () => tf.constant[Boolean](false)) }) case (Some(thisFilter), None) => Some(thisFilter) case (None, Some(otherFilter)) => Some(otherFilter) case (None, None) => None } } } } } object Curriculum { def none[T]: Curriculum[T] = { new Curriculum[T] {} } }
2,216
28.56
107
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/curriculum/SentencePairCurriculum.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.curriculum import org.platanios.symphony.mt.data.scores.SentenceScore import org.platanios.symphony.mt.models.SentencePairsWithScores import org.platanios.symphony.mt.models.curriculum.competency.Competency import org.platanios.tensorflow.api.Output /** * @author Emmanouil Antonios Platanios */ class SentencePairCurriculum( override val competency: Competency[Output[Float]], override val score: SentenceScore, val scoreSelector: SentencePairCurriculum.ScoreSelector, override val maxNumHistogramBins: Int = 1000 ) extends DifficultyBasedCurriculum[SentencePairsWithScores[String]]( competency = competency, score = score, maxNumHistogramBins = maxNumHistogramBins ) { override protected def sampleScore(sample: SentencePairsWithScores[String]): Output[Float] = { scoreSelector match { case SentencePairCurriculum.SourceSentenceScore => sample._2._3.get case SentencePairCurriculum.TargetSentenceScore => sample._3._3.get } } } object SentencePairCurriculum { sealed trait ScoreSelector object SourceSentenceScore extends ScoreSelector object TargetSentenceScore extends ScoreSelector def apply( competency: Competency[Output[Float]], score: SentenceScore, scoreSelector: ScoreSelector, maxNumHistogramBins: Int = 1000 ): SentencePairCurriculum = { new SentencePairCurriculum(competency, score, scoreSelector, maxNumHistogramBins) } }
2,108
35.362069
96
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/curriculum/competency/LinearStepCompetency.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.curriculum.competency import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ class LinearStepCompetency[T: TF : IsNotQuantized]( val initialValue: T, val numStepsToFullCompetency: T ) extends Competency[Output[T]] { override def currentLevel(step: Output[Long]): Output[T] = { val zero = tf.zeros[T](Shape()) val one = tf.ones[T](Shape()) val c0 = tf.constant[T](initialValue) val T = tf.constant[T](numStepsToFullCompetency) val t = step.castTo[T] tf.maximum(tf.minimum((t * (one - c0) / T) + c0, one), zero) } }
1,262
34.083333
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/curriculum/competency/Competency.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.curriculum.competency import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ trait Competency[Level] { def currentLevel(step: Output[Long]): Level }
863
32.230769
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/curriculum/competency/ExponentialStepCompetency.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.curriculum.competency import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ class ExponentialStepCompetency[T: TF : IsNotQuantized]( val initialValue: T, val numStepsToFullCompetency: T, val power: Int ) extends Competency[Output[T]] { override def currentLevel(step: Output[Long]): Output[T] = { val zero = tf.zeros[T](Shape()) val one = tf.ones[T](Shape()) val p = tf.constant[Int](power).castTo[T] val c0Pow = tf.pow(tf.constant[T](initialValue), p) val T = tf.constant[T](numStepsToFullCompetency) val t = step.castTo[T] tf.maximum(tf.minimum(tf.pow((t * (one - c0Pow) / T) + c0Pow, one / p), one), zero) } }
1,370
35.078947
87
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/TransformerEncoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer import org.platanios.symphony.mt.models.Transformation.Encoder import org.platanios.symphony.mt.models._ import org.platanios.symphony.mt.models.Utilities._ import org.platanios.symphony.mt.models.transformer.helpers._ import org.platanios.symphony.mt.models.helpers.Common import org.platanios.tensorflow.api._ /** Transformer encoder. * * This encoder takes as input a source sequence in some language and returns a tuple containing: * - '''Output:''' Outputs (for each time step) of the transformer. * - '''State:''' Empty sequence * * @author Emmanouil Antonios Platanios */ class TransformerEncoder[T: TF : IsHalfOrFloatOrDouble]( val numUnits: Int, val numLayers: Int, val useSelfAttentionProximityBias: Boolean = false, val positionEmbeddings: PositionEmbeddings = FixedSinusoidPositionEmbeddings(1.0f, 1e4f), val postPositionEmbeddingsDropout: Float = 0.1f, val usePadRemover: Boolean = true, val layerPreprocessors: Seq[LayerProcessor] = Seq( Normalize(LayerNormalization(), 1e-6f)), val layerPostprocessors: Seq[LayerProcessor] = Seq( Dropout(0.1f, broadcastAxes = Set.empty), AddResidualConnection), val removeFirstLayerResidualConnection: Boolean = false, val attentionKeysDepth: Int = 128, val attentionValuesDepth: Int = 128, val attentionNumHeads: Int = 8, val selfAttention: Attention = DotProductAttention(0.1f, Set.empty, "DotProductAttention"), val feedForwardLayer: FeedForwardLayer = DenseReLUDenseFeedForwardLayer(256, 128, 0.1f, Set.empty, "FeedForward") ) extends Encoder[EncodedSequences[T]] { override def apply(sequences: Sequences[Int])(implicit context: ModelConstructionContext): EncodedSequences[T] = { // `embeddedSequences.sequences` has shape [batchSize, maxLength, wordEmbeddingSize] // `embeddedSequence.lengths` has shape [batchSize] val wordEmbeddingsSize = context.parameterManager.wordEmbeddingsType.embeddingsSize var embeddedSequences = embedSrcSequences(sequences) if (wordEmbeddingsSize != numUnits) { val projectionWeights = context.parameterManager.get[Float]( "ProjectionToEncoderNumUnits", Shape(wordEmbeddingsSize, numUnits)) val projectedSequences = Common.matrixMultiply(embeddedSequences.sequences, projectionWeights) // `embeddedSequences.sequences` has shape [batchSize, maxLength, numUnits] embeddedSequences = embeddedSequences.copy(sequences = projectedSequences) } val embeddedSequencesMaxLength = tf.shape(embeddedSequences.sequences).slice(1) // Perform some pre-processing to the token embeddings sequence. val padding = tf.logicalNot( tf.sequenceMask(embeddedSequences.lengths, embeddedSequencesMaxLength, name = "Padding")).toFloat var encoderSelfAttentionBias = Attention.attentionBiasIgnorePadding(padding) if (useSelfAttentionProximityBias) encoderSelfAttentionBias += Attention.attentionBiasProximal(embeddedSequencesMaxLength) var encoderInput = positionEmbeddings.addTo(embeddedSequences.sequences) if (context.mode.isTraining) encoderInput = tf.dropout(encoderInput, 1.0f - postPositionEmbeddingsDropout) // Add the multi-head attention and the feed-forward layers. val padRemover = if (usePadRemover && !Common.isOnTPU) Some(PadRemover(padding)) else None var x = encoderInput var y = x (0 until numLayers).foreach(layer => { tf.variableScope(s"Layer$layer") { tf.variableScope("SelfAttention") { val queryAntecedent = LayerProcessor.layerPreprocess(x, layerPreprocessors) y = Attention.multiHeadAttention( queryAntecedent = queryAntecedent, memoryAntecedent = None, bias = encoderSelfAttentionBias, totalKeysDepth = attentionKeysDepth, totalValuesDepth = attentionValuesDepth, outputsDepth = numUnits, numHeads = attentionNumHeads, attention = selfAttention, name = "MultiHeadAttention")._1 if (layer == 0 && removeFirstLayerResidualConnection) x = LayerProcessor.layerPostprocess(x, y, layerPostprocessors.filter(_ != AddResidualConnection)) else x = LayerProcessor.layerPostprocess(x, y, layerPostprocessors) } tf.variableScope("FeedForward") { val xx = LayerProcessor.layerPreprocess(x, layerPreprocessors) y = feedForwardLayer(xx.toFloat, padRemover) x = LayerProcessor.layerPostprocess(x, y, layerPostprocessors) } } }) // If normalization is done during layer preprocessing, then it should also be done on the output, since the output // can grow very large, being the sum of a whole stack of unnormalized layer outputs. val encoderOutput = LayerProcessor.layerPreprocess(x, layerPreprocessors) EncodedSequences(encoderOutput.castTo[T], embeddedSequences.lengths) } }
5,627
47.517241
119
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/package.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models import org.platanios.tensorflow.api.Output /** * @author Emmanouil Antonios Platanios */ package object transformer { case class EncodedSequences[T]( states: Output[T], lengths: Output[Int]) }
890
30.821429
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/TransformerDecoder.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.symphony.mt.models.Transformation.Decoder import org.platanios.symphony.mt.models.decoders.{BasicDecoder, BeamSearchDecoder, OutputLayer, ProjectionToWords} import org.platanios.symphony.mt.models.helpers.Common import org.platanios.symphony.mt.models.transformer.helpers.Attention.MultiHeadAttentionCache import org.platanios.symphony.mt.models.transformer.helpers._ import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.tf.{RNNCell, RNNTuple} /** * @author Emmanouil Antonios Platanios */ class TransformerDecoder[T: TF : IsHalfOrFloatOrDouble]( val numUnits: Int, val numLayers: Int, val useSelfAttentionProximityBias: Boolean = false, val positionEmbeddings: PositionEmbeddings = FixedSinusoidPositionEmbeddings(1.0f, 1e4f), val postPositionEmbeddingsDropout: Float = 0.1f, val layerPreprocessors: Seq[LayerProcessor] = Seq( Normalize(LayerNormalization(), 1e-6f)), val layerPostprocessors: Seq[LayerProcessor] = Seq( Dropout(0.1f, broadcastAxes = Set.empty), AddResidualConnection), val removeFirstLayerResidualConnection: Boolean = false, val attentionKeysDepth: Int = 128, val attentionValuesDepth: Int = 128, val attentionNumHeads: Int = 8, val selfAttention: Attention = DotProductAttention(0.1f, Set.empty, "DotProductAttention"), val feedForwardLayer: FeedForwardLayer = DenseReLUDenseFeedForwardLayer(256, 128, 0.1f, Set.empty, "FeedForward"), val useEncoderDecoderAttentionCache: Boolean = true, val outputLayer: OutputLayer = ProjectionToWords ) extends Decoder[EncodedSequences[T]] { override def applyTrain( encodedSequences: EncodedSequences[T] )(implicit context: ModelConstructionContext): Sequences[Float] = { // TODO: What if no target sequences are provided? val tgtSequences = context.tgtSequences.get // Shift the target sequence one step forward so the decoder learns to output the next word. val tgtBosId = tf.constant[Int](Vocabulary.BEGIN_OF_SEQUENCE_TOKEN_ID) val batchSize = tf.shape(tgtSequences.sequences).slice(0) val shiftedTgtSequences = tf.concatenate(Seq( tf.fill[Int, Int](tf.stack[Int](Seq(batchSize, 1)))(tgtBosId), tgtSequences.sequences), axis = 1) val shiftedTgtSequencesMaxLength = tf.shape(shiftedTgtSequences).slice(1) // Embed the target sequences. val embeddedTgtSequences = embeddings(shiftedTgtSequences) // Perform some pre-processing to the token embeddings sequence. var decoderSelfAttentionBias = Attention.attentionBiasLowerTriangular(shiftedTgtSequencesMaxLength) if (useSelfAttentionProximityBias) decoderSelfAttentionBias += Attention.attentionBiasProximal(shiftedTgtSequencesMaxLength) var decoderInputSequences = positionEmbeddings.addTo(embeddedTgtSequences) if (context.mode.isTraining) decoderInputSequences = tf.dropout(decoderInputSequences, 1.0f - postPositionEmbeddingsDropout) // Project the decoder input sequences, if necessary. val wordEmbeddingsSize = context.parameterManager.wordEmbeddingsType.embeddingsSize if (wordEmbeddingsSize != numUnits) { val projectionWeights = context.parameterManager.get[T]( "ProjectionToDecoderNumUnits", Shape(wordEmbeddingsSize, numUnits)) decoderInputSequences = Common.matrixMultiply(decoderInputSequences, projectionWeights) } // Project the encoder output, if necessary. var encoderOutput = encodedSequences.states if (numUnits != encoderOutput.shape(-1)) { val projectionWeights = context.parameterManager.get[T]( "ProjectionToDecoderNumUnits", Shape(encoderOutput.shape(-1), numUnits)) encoderOutput = Common.matrixMultiply(encoderOutput, projectionWeights) } val encodedSequencesMaxLength = tf.shape(encoderOutput).slice(1) val inputPadding = tf.logicalNot( tf.sequenceMask(encodedSequences.lengths, encodedSequencesMaxLength, name = "Padding")).toFloat val encoderDecoderAttentionBias = Attention.attentionBiasIgnorePadding(inputPadding) // Obtain the output projection layer weights. val outputLayer = this.outputLayer(numUnits) // Pre-compute the encoder-decoder attention keys and values. val encoderDecoderAttentionCache = (0 until numLayers).map(layer => { tf.variableScope(s"Layer$layer/EncoderDecoderAttention/Cache") { val encoderDecoderAttentionKeys = Attention.computeAttentionComponent( encoderOutput, attentionKeysDepth, name = "K").toFloat val encoderDecoderAttentionValues = Attention.computeAttentionComponent( encoderOutput, attentionValuesDepth, name = "V").toFloat MultiHeadAttentionCache( keys = Attention.splitHeads(encoderDecoderAttentionKeys, attentionNumHeads), values = Attention.splitHeads(encoderDecoderAttentionValues, attentionNumHeads)) } }) // Finally, apply the decoding model. val (decodedSequences, _) = decode( encoderOutput = encoderOutput.toFloat, decoderInputSequences = decoderInputSequences, decoderSelfAttentionBias = decoderSelfAttentionBias, decoderSelfAttentionCache = None, encoderDecoderAttentionBias = encoderDecoderAttentionBias, encoderDecoderAttentionCache = Some(encoderDecoderAttentionCache)) val outputSequences = outputLayer(decodedSequences) Sequences(outputSequences.toFloat, encodedSequences.lengths) } override def applyInfer( encodedSequences: EncodedSequences[T] )(implicit context: ModelConstructionContext): Sequences[Int] = { val wordEmbeddingsSize = context.parameterManager.wordEmbeddingsType.embeddingsSize // Project the encoder output, if necessary. var encoderOutput = encodedSequences.states if (numUnits != encoderOutput.shape(-1)) { val projectionWeights = context.parameterManager.get[T]( "ProjectionToDecoderNumUnits", Shape(encoderOutput.shape(-1), numUnits)) encoderOutput = Common.matrixMultiply(encoderOutput, projectionWeights) } // Determine the maximum allowed sequence length to consider while decoding. val maxDecodingLength = { if (!context.mode.isTraining && context.dataConfig.tgtMaxLength != -1) tf.constant(context.dataConfig.tgtMaxLength) else tf.round(tf.max(encodedSequences.lengths).toFloat * context.inferenceConfig.maxDecodingLengthFactor).toInt } val positionEmbeddings = this.positionEmbeddings.get(maxDecodingLength + 1, wordEmbeddingsSize).castTo[T] var decoderSelfAttentionBias = Attention.attentionBiasLowerTriangular(maxDecodingLength) if (useSelfAttentionProximityBias) decoderSelfAttentionBias += Attention.attentionBiasProximal(maxDecodingLength) // Pre-compute the encoder-decoder attention keys and values. val encoderDecoderAttentionCache = (0 until numLayers).map(layer => { tf.variableScope(s"Layer$layer/EncoderDecoderAttention/Cache") { val encoderDecoderAttentionKeys = Attention.computeAttentionComponent( encoderOutput, attentionKeysDepth, name = "K").toFloat val encoderDecoderAttentionValues = Attention.computeAttentionComponent( encoderOutput, attentionValuesDepth, name = "V").toFloat MultiHeadAttentionCache( keys = Attention.splitHeads(encoderDecoderAttentionKeys, attentionNumHeads), values = Attention.splitHeads(encoderDecoderAttentionValues, attentionNumHeads)) } }) // Create the decoder RNN cell. val zero = tf.constant[Int](0) val one = tf.constant[Int](1) val cell = new RNNCell[ Output[T], (EncodedSequences[T], Output[Int], Seq[MultiHeadAttentionCache[Float]], Seq[MultiHeadAttentionCache[Float]]), Shape, ((Shape, Shape), Shape, Seq[(Shape, Shape)], Seq[(Shape, Shape)])] { override def outputShape: Shape = { Shape(numUnits) } override def stateShape: ((Shape, Shape), Shape, Seq[(Shape, Shape)], Seq[(Shape, Shape)]) = { ((Shape(-1, numUnits), Shape()), Shape(), (0 until numLayers).map(_ => (Shape(attentionNumHeads, -1, attentionKeysDepth / attentionNumHeads), Shape(attentionNumHeads, -1, attentionValuesDepth / attentionNumHeads))), (0 until numLayers).map(_ => (Shape(attentionNumHeads, -1, attentionKeysDepth / attentionNumHeads), Shape(attentionNumHeads, -1, attentionValuesDepth / attentionNumHeads)))) } override def forward( input: RNNTuple[Output[T], (EncodedSequences[T], Output[Int], Seq[MultiHeadAttentionCache[Float]], Seq[MultiHeadAttentionCache[Float]])] ): RNNTuple[Output[T], (EncodedSequences[T], Output[Int], Seq[MultiHeadAttentionCache[Float]], Seq[MultiHeadAttentionCache[Float]])] = { val encodedSequences = input.state._1 val encodedSequencesMaxLength = tf.shape(encodedSequences.states).slice(1) val inputPadding = tf.logicalNot( tf.sequenceMask(encodedSequences.lengths, encodedSequencesMaxLength, name = "Padding")).toFloat val encoderDecoderAttentionBias = Attention.attentionBiasIgnorePadding(inputPadding) // This is necessary in order to deal with the beam search tiling. val step = input.state._2(0) val currentStepPositionEmbeddings = positionEmbeddings(0).gather(step).expandDims(0).expandDims(1) var currentStepInput = input.output.expandDims(1) + currentStepPositionEmbeddings // Project the decoder input sequences, if necessary. val wordEmbeddingsSize = context.parameterManager.wordEmbeddingsType.embeddingsSize if (wordEmbeddingsSize != numUnits) { val projectionWeights = context.parameterManager.get[T]( "ProjectionToDecoderNumUnits", Shape(wordEmbeddingsSize, numUnits)) currentStepInput = Common.matrixMultiply(currentStepInput, projectionWeights) } val selfAttentionBias = tf.slice( decoderSelfAttentionBias(0, 0, ::, ::).gather(step), Seq(zero), Seq(step + one)) val (output, updatedMultiHeadAttentionCache) = decode( encoderOutput = input.state._1.states.toFloat, decoderInputSequences = currentStepInput, decoderSelfAttentionBias = selfAttentionBias, decoderSelfAttentionCache = Some(input.state._3), encoderDecoderAttentionBias = encoderDecoderAttentionBias, encoderDecoderAttentionCache = Some(input.state._4)) val currentStepOutput = output.squeeze(Seq(1)) RNNTuple( output = currentStepOutput, state = (input.state._1, input.state._2 + one, updatedMultiHeadAttentionCache.map(_.get), input.state._4)) } } // Create some constants that will be used during decoding. val tgtBosID = tf.constant[Int](Vocabulary.BEGIN_OF_SEQUENCE_TOKEN_ID) val tgtEosID = tf.constant[Int](Vocabulary.END_OF_SEQUENCE_TOKEN_ID) // Initialize the cache and the decoder RNN state. val embeddings = (ids: Output[Int]) => this.embeddings(ids) val batchSize = tf.shape(encodedSequences.lengths).slice(0) val decoderSelfAttentionCache = (0 until numLayers).map(_ => { MultiHeadAttentionCache( keys = Attention.splitHeads( tf.zeros[Float](tf.stack[Int](Seq(batchSize, zero, attentionKeysDepth))), attentionNumHeads), values = Attention.splitHeads( tf.zeros[Float](tf.stack[Int](Seq(batchSize, zero, attentionValuesDepth))), attentionNumHeads)) }) val initialState = ( encodedSequences.copy(states = encoderOutput), tf.zeros[Int](batchSize.expandDims(0)), decoderSelfAttentionCache, encoderDecoderAttentionCache) // Create the decoder RNN. val output = { if (context.inferenceConfig.beamWidth > 1) { val decoder = BeamSearchDecoder( cell, initialState, embeddings, tf.fill[Int, Int](batchSize.expandDims(0))(tgtBosID), tgtEosID, context.inferenceConfig.beamWidth, context.inferenceConfig.lengthPenalty, outputLayer(numUnits)) val tuple = decoder.decode( outputTimeMajor = false, maximumIterations = maxDecodingLength, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory) Sequences(tuple._1.predictedIDs(---, 0), tuple._3(---, 0).toInt) } else { val decHelper = BasicDecoder.GreedyEmbeddingHelper[T, (EncodedSequences[T], Output[Int], Seq[MultiHeadAttentionCache[Float]], Seq[MultiHeadAttentionCache[Float]])]( embeddingFn = embeddings, beginTokens = tf.fill[Int, Int](batchSize.expandDims(0))(tgtBosID), endToken = tgtEosID) val decoder = BasicDecoder(cell, initialState, decHelper, outputLayer(numUnits)) val tuple = decoder.decode( outputTimeMajor = false, maximumIterations = maxDecodingLength, parallelIterations = context.env.parallelIterations, swapMemory = context.env.swapMemory) Sequences(tuple._1.sample, tuple._3) } } Sequences(output.sequences(---, 0 :: -1), output.lengths - 1) } protected def embeddings( ids: Output[Int] )(implicit context: ModelConstructionContext): Output[T] = { context.parameterManager.wordEmbeddings(context.tgtLanguageID, ids).castTo[T] } protected def decode( encoderOutput: Output[Float], decoderInputSequences: Output[T], decoderSelfAttentionBias: Output[Float], decoderSelfAttentionCache: Option[Seq[MultiHeadAttentionCache[Float]]], encoderDecoderAttentionBias: Output[Float], encoderDecoderAttentionCache: Option[Seq[MultiHeadAttentionCache[Float]]] )(implicit context: ModelConstructionContext): (Output[T], Seq[Option[MultiHeadAttentionCache[Float]]]) = { // Add the multi-head attention and the feed-forward layers. var x = decoderInputSequences.toFloat var y = x val updatedDecoderSelfAttentionCache = (0 until numLayers).map(layer => { tf.variableScope(s"Layer$layer") { val updatedDecoderSelfAttentionCache = tf.variableScope("SelfAttention") { val queryAntecedent = LayerProcessor.layerPreprocess(x, layerPreprocessors) val (output, updatedDecoderSelfAttentionCache) = Attention.multiHeadAttention( queryAntecedent = queryAntecedent, memoryAntecedent = None, bias = decoderSelfAttentionBias, totalKeysDepth = attentionKeysDepth, totalValuesDepth = attentionValuesDepth, outputsDepth = numUnits, numHeads = attentionNumHeads, attention = selfAttention, cache = decoderSelfAttentionCache.map(_ (layer)), name = "MultiHeadAttention") y = output if (layer == 0 && removeFirstLayerResidualConnection) x = LayerProcessor.layerPostprocess(x, y, layerPostprocessors.filter(_ != AddResidualConnection)) else x = LayerProcessor.layerPostprocess(x, y, layerPostprocessors) updatedDecoderSelfAttentionCache } tf.variableScope("EncoderDecoderAttention") { val queryAntecedent = LayerProcessor.layerPreprocess(x, layerPreprocessors) y = Attention.multiHeadAttention( queryAntecedent = queryAntecedent, memoryAntecedent = Some(encoderOutput), bias = encoderDecoderAttentionBias, totalKeysDepth = attentionKeysDepth, totalValuesDepth = attentionValuesDepth, outputsDepth = numUnits, numHeads = attentionNumHeads, attention = selfAttention, cache = encoderDecoderAttentionCache.map(_ (layer)), name = "MultiHeadAttention")._1 x = LayerProcessor.layerPostprocess(x, y, layerPostprocessors) } tf.variableScope("FeedForward") { val xx = LayerProcessor.layerPreprocess(x, layerPreprocessors) // TODO: What about the pad remover? y = feedForwardLayer(xx, None) x = LayerProcessor.layerPostprocess(x, y, layerPostprocessors) } updatedDecoderSelfAttentionCache } }) // If normalization is done during layer preprocessing, then it should also be done on the output, since the // output can grow very large, being the sum of a whole stack of unnormalized layer outputs. (LayerProcessor.layerPreprocess(x, layerPreprocessors).castTo[T], updatedDecoderSelfAttentionCache) } }
17,399
49.144092
172
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/helpers/DotProductAttention.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer.helpers import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.models.helpers.Common import org.platanios.tensorflow.api._ /** Dot-product attention. * * @param dropoutRate Dropout rate for the attention weights. * @param dropoutBroadcastAxes Specifies along which axes of the attention weights the dropout is broadcast. * @param name Name for this attention model that also specifies a variable scope. * * @author Emmanouil Antonios Platanios */ class DotProductAttention protected ( val dropoutRate: Float = 0.0f, val dropoutBroadcastAxes: Set[Int] = Set.empty, val name: String = "DotProductAttention" ) extends Attention { /** Computes the attention for the provided queries, keys, and values. * * @param q Queries tensor with shape `[batchSize, ..., length, depth]`. * @param k Keys tensor with shape `[batchSize, ..., length, depth]`. * @param v Values tensor with shape `[batchSize, ..., length, depth]`. * @param bias Optional attention bias. * @return Attention tensor with shape `[batchSize, ..., length, depth]`. */ override def apply[T: TF : IsHalfOrFloatOrDouble]( q: Output[T], k: Output[T], v: Output[T], bias: Option[Output[T]] )(implicit context: ModelConstructionContext): Output[T] = { tf.nameScope(name) { // `logits` shape: [batchSize, numHeads, queryLength, memoryLength] var logits = tf.matmul(q, k, transposeB = true) bias.foreach(logits += _) var weights = tf.softmax(logits, name = "AttentionWeights") // Apply dropout to the attention links for each of the heads. if (context.mode.isTraining) weights = Common.dropoutWithBroadcastAxes(weights, 1.0f - dropoutRate, broadcastAxes = dropoutBroadcastAxes) tf.matmul(weights, v) } } } object DotProductAttention { def apply( dropoutRate: Float = 0.0f, dropoutBroadcastAxes: Set[Int] = Set.empty, name: String = "DotProductAttention" ): DotProductAttention = { new DotProductAttention(dropoutRate, dropoutBroadcastAxes, name) } }
2,849
39.140845
116
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/helpers/AttentionPrependMode.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer.helpers import org.platanios.tensorflow.api._ /** The attention prepend mode is a mechanism that allows us to optionally treat a sequence-to-sequence model as a * language model. It allows us to prepend the inputs to the targets, while performing decoding. * * @author Emmanouil Antonios Platanios */ trait AttentionPrependMode { /** Creates a bias tensor to be added to the attention logits. * * @param padding Tensor with shape `[batchSize, length]`, with ones in positions corresponding to * padding and zeros otherwise. In each row of this tensor, a single padding position separates the * input part from the target part. * @return Tensor with shape `[batchSize, 1, length, length]`. */ def apply(padding: Output[Float]): Output[Float] } /** Creates a bias tensor to be added to the attention logits, that allows for full connectivity in the "inputs" part of * the sequence and for masked connectivity in the targets part. */ case object AttentionPrependInputsFullAttention extends AttentionPrependMode { /** Creates a bias tensor to be added to the attention logits. * * @param padding Tensor with shape `[batchSize, length]`, with ones in positions corresponding to * padding and zeros otherwise. In each row of this tensor, a single padding position separates the * input part from the target part. * @return Tensor with shape `[batchSize, 1, length, length]`. */ override def apply(padding: Output[Float]): Output[Float] = { // Everything past the first padding position is part of the target. This tensor has zeros for the source portion // and the separator, and ones for the target portion. val inTarget = tf.cumsum(padding, axis = 1, exclusive = true) // Position within the target, or 0 if part of the source. val targetPositions = tf.cumsum(inTarget, axis = 1) // A position with a lesser `targetPosition` cannot see a position with a greater `targetPosition`. val illegalConnections = tf.greater( tf.expandDims(targetPositions, axis = 1), tf.expandDims(targetPositions, axis = 2)) tf.expandDims(illegalConnections.toFloat * -1e9f, axis = 1) } } /** Creates a bias tensor to be added to the attention logits, that allows allows a query to attend to all positions up * to and including its own. */ case object AttentionPrependInputsMaskedAttention extends AttentionPrependMode { /** Creates a bias tensor to be added to the attention logits. * * @param padding Tensor with shape `[batchSize, length]`, with ones in positions corresponding to * padding and zeros otherwise. In each row of this tensor, a single padding position separates the * input part from the target part. * @return Tensor with shape `[1, 1, length, length]`. */ override def apply(padding: Output[Float]): Output[Float] = { Attention.attentionBiasLowerTriangular(tf.shape(padding).slice(1)) } }
3,720
49.283784
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/helpers/PositionEmbeddings.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer.helpers import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ trait PositionEmbeddings { // TODO: !!! Add name to positional embeddings. def get( length: Output[Int], depth: Output[Int] ): Output[Float] def addTo[T: TF : IsNotQuantized]( input: Output[T], positions: Option[Output[Int]] = None ): Output[T] } object PositionEmbeddings { /** Creates a bunch of sinusoids of different frequencies and phases, to be used as positional embeddings. * * This allows attention models to learn and use absolute and relative positions. Positional embeddings should be * added to some precursors of both the query and the memory inputs to attention. * * The use of relative position is possible because `sin(x + y)` and `cos(x + y)` can be expressed in terms of `y`, * `sin(x)` and `cos(x)`. * * In particular, we use a geometric sequence of scales starting with `minScale` and ending with `maxScale`. The * number of different scales is equal to `depth / 2`. For each scale, we generate the two sinusoidal signals * `sin(position / scale)` and `cos(position / scale)`. All of these sinusoids are concatenated along the depth * dimension. * * @param length Length of the input sequences. * @param depth Depth of the input sequences (i.e., number of channels). * @param minScale Minimum scale. * @param maxScale Maximum scale. * @return Positional embeddings tensor with shape `[1, length, depth]`. */ def positionalEmbeddings1D( length: Output[Int], depth: Output[Int], minScale: Float = 1.0f, maxScale: Float = 1.0e4f ): Output[Float] = { val zero = tf.constant[Int](0) val one = tf.constant[Int](1) val two = tf.constant[Int](2) val positions = tf.range(zero, length).toFloat val numScales = tf.truncateDivide(depth, two) val logScaleIncrement = math.log(maxScale / minScale).toFloat / (numScales - one).toFloat val invScales = minScale * tf.exp(-tf.range(zero, numScales).toFloat * logScaleIncrement) val scaledPositions = tf.expandDims(positions, axis = one) * tf.expandDims(invScales, axis = zero) var embedding = tf.concatenate(Seq(tf.sin(scaledPositions), tf.cos(scaledPositions)), axis = one) val padding = tf.stack(Seq(tf.stack(Seq(zero, zero)), tf.stack(Seq(zero, tf.mod(depth, two))))) embedding = tf.pad(embedding, padding) embedding = embedding.reshape(tf.stack(Seq(one, length, depth))) embedding } /** Adds a bunch of sinusoids of different frequencies and phases to `input`. * * Each channel (i.e., 3rd dimension) of the input tensor is incremented by a sinusoid of a different frequency and * phase. * * This allows attention models to learn and use absolute and relative positions. Positional embeddings should be * added to some precursors of both the query and the memory inputs to attention. * * The use of relative position is possible because `sin(x + y)` and `cos(x + y)` can be expressed in terms of `y`, * `sin(x)` and `cos(x)`. * * In particular, we use a geometric sequence of scales starting with `minScale` and ending with `maxScale`. The * number of different scales is equal to `depth / 2`. For each scale, we generate the two sinusoidal signals * `sin(position / scale)` and `cos(position / scale)`. All of these sinusoids are concatenated along the depth * dimension. * * @param input Input tensor with shape `[batchSize, length, depth]`. * @param minScale Minimum scale. * @param maxScale Maximum scale. * @return Input tensor with the positional embeddings added to it. */ def addPositionalEmbeddings1D[T: TF : IsNotQuantized]( input: Output[T], minScale: Float = 1.0f, maxScale: Float = 1.0e4f ): Output[T] = { val inputShape = tf.shape(input) val length = inputShape(1) val depth = inputShape(2) val embedding = positionalEmbeddings1D(length, depth, minScale, maxScale) input + embedding.castTo[T] } /** Adds a bunch of sinusoids of different frequencies and phases to `input`, using the provided positions. * * @param input Input tensor with shape `[batchSize, length, depth]`. * @param positions Positions tensor with shape `[batchSize, length]`. * @param minScale Minimum scale. * @param maxScale Maximum scale. * @return Input tensor with the positional embeddings added to it. */ def addPositionalEmbeddings1DGivenPositions[T: TF : IsNotQuantized]( input: Output[T], positions: Output[Int], minScale: Float = 1.0f, maxScale: Float = 1.0e4f ): Output[T] = { val inputShape = tf.shape(input).toInt val depth = inputShape(2).toInt val zero = tf.constant[Int](0) val one = tf.constant[Int](1) val two = tf.constant[Int](2) val numScales = tf.truncateDivide(depth, two).toInt val logScaleIncrement = math.log(maxScale / minScale).toFloat / (numScales - one).toFloat val invScales = minScale * tf.exp(-tf.range(zero, numScales).toFloat * logScaleIncrement) val scaledPositions = tf.expandDims(positions.toFloat, axis = two) * tf.expandDims(tf.expandDims(invScales, axis = zero), axis = zero) val embedding = tf.concatenate(Seq(tf.sin(scaledPositions), tf.cos(scaledPositions)), axis = two) val padding = tf.stack(Seq( tf.stack(Seq(zero, zero)), tf.stack(Seq(zero, zero)), tf.stack(Seq(zero, tf.mod(depth, two).toInt)))) input + tf.pad(embedding, padding).castTo[T] } /** Adds a bunch of sinusoids of different frequencies and phases to `input`. * * Each channel (i.e., 3rd dimension) of the input tensor is incremented by a sinusoid of a different frequency and * phase. * * This allows attention models to learn and use absolute and relative positions. Positional embeddings should be * added to some precursors of both the query and the memory inputs to attention. * * The use of relative position is possible because `sin(x + y)` and `cos(x + y)` can be expressed in terms of `y`, * `sin(x)` and `cos(x)`. * * `input` is a tensor with `n` "positional" dimensions (e.g., one for a sequence or two for an image). * * In particular, we use a geometric sequence of scales starting with `minScale` and ending with `maxScale`. The * number of different scales is equal to `depth / (n * 2)`. For each scale, we generate the two sinusoidal signals * `sin(position / scale)` and `cos(position / scale)`. All of these sinusoids are concatenated along the depth * dimension. * * @param input Input tensor with shape `[batchSize, d1, ..., dn, depth]`. * @param minScale Minimum scale. * @param maxScale Maximum scale. * @return Input tensor with the positional embeddings added to it. */ def addPositionalEmbeddingsND[T: TF : IsNotQuantized]( input: Output[T], minScale: Float = 1.0f, maxScale: Float = 1.0e4f ): Output[T] = { val rank = input.rank - 2 val inputShape = tf.shape(input).toInt val depth = inputShape(-1) val zero = tf.constant[Int](0) val one = tf.constant[Int](1) val two = tf.constant[Int](2) val minusTwo = tf.constant[Int](-2) val numScales = tf.truncateDivide(depth, two * rank).toInt val logScaleIncrement = math.log(maxScale / minScale).toFloat / (numScales - one).toFloat val invScales = minScale * tf.exp(-tf.range(zero, numScales).toFloat * logScaleIncrement) var result = input (0 until rank).foreach(axis => { val length = inputShape(axis + 1) val positions = tf.range(zero, length).toFloat val scaledPositions = tf.expandDims(positions, axis = one) * tf.expandDims(invScales, axis = zero) var embedding = tf.concatenate(Seq(tf.sin(scaledPositions), tf.cos(scaledPositions)), axis = one) val prePadding = 2 * rank * numScales val postPadding = depth - (axis + 1) * 2 * numScales embedding = tf.pad(embedding, tf.stack(Seq( tf.stack(Seq(zero, zero)), tf.stack(Seq(prePadding, postPadding)) ))) (0 until axis + 1).foreach(_ => embedding = tf.expandDims(embedding, axis = zero)) (0 until rank - 1 - axis).foreach(_ => embedding = tf.expandDims(embedding, axis = minusTwo)) result += embedding.castTo[T] }) result } } class FixedSinusoidPositionEmbeddings protected ( val minScale: Float = 1.0f, val maxScale: Float = 1.0e4f ) extends PositionEmbeddings { override def get( length: Output[Int], depth: Output[Int] ): Output[Float] = { PositionEmbeddings.positionalEmbeddings1D(length, depth, minScale, maxScale) } override def addTo[T: TF : IsNotQuantized]( input: Output[T], positions: Option[Output[Int]] = None ): Output[T] = { positions match { case Some(p) => PositionEmbeddings.addPositionalEmbeddings1DGivenPositions(input, p, minScale, maxScale) case None => PositionEmbeddings.addPositionalEmbeddings1D(input, minScale, maxScale) } } } object FixedSinusoidPositionEmbeddings { def apply(minScale: Float = 1.0f, maxScale: Float = 1.0e4f): FixedSinusoidPositionEmbeddings = { new FixedSinusoidPositionEmbeddings(minScale, maxScale) } }
10,027
42.982456
118
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/helpers/Attention.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer.helpers import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.models.helpers.Common import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.ops.NN.{ConvPaddingMode, ValidConvPadding} import scala.language.postfixOps /** * @author Emmanouil Antonios Platanios */ trait Attention { /** Computes the attention for the provided queries, keys, and values. * * @param q Queries tensor with shape `[batchSize, ..., length, depth]`. * @param k Keys tensor with shape `[batchSize, ..., length, depth]`. * @param v Values tensor with shape `[batchSize, ..., length, depth]`. * @param bias Optional attention bias. * @return Attention tensor with shape `[batchSize, ..., length, depth]`. */ def apply[T: TF : IsHalfOrFloatOrDouble]( q: Output[T], k: Output[T], v: Output[T], bias: Option[Output[T]] )(implicit context: ModelConstructionContext): Output[T] // TODO: Add support for saving weights. // TODO: Add support for image summaries for the weights. } object Attention { //region Attention Bias /** Creates a bias tensor to be added to the attention logits. * * A position may attend to positions of at most some distance from it (forwards and backwards). * * @param length Integer scalar representing the sequence length. * @param maxBackward Maximum backwards distance to attend. Negative values indicate an unlimited distance. * @param maxForward Maximum forwards distance to attend. Negative values indicate an unlimited distance. * @return Tensor with shape `[1, 1, length, length]`. */ def attentionBiasLocal( length: Output[Int], maxBackward: Int, maxForward: Int ): Output[Float] = { var band = tf.matrixBandPart( tf.ones[Float, Int](tf.stack[Int](Seq(length, length))), tf.constant[Int](maxBackward), tf.constant[Int](maxForward)) band = tf.reshape(band, tf.stack[Int](Seq(1, 1, length, length))) tf.constant[Float](-1e9f) * (1.0f - band) } /** Creates a bias tensor to be added to the attention logits. * * This bias allows a query to attend to all positions up to and including its own. * * @param length Integer scalar representing the sequence length. * @return Tensor with shape `[1, 1, length, length]`. */ def attentionBiasLowerTriangular( length: Output[Int] ): Output[Float] = { attentionBiasLocal(length, -1, 0) } /** Creates a bias tensor to be added to the attention logits. * * This bias allows positions with the same segment IDs to see each other. * * @param querySegmentIDs Tensor with shape `[batchSize, queryLength]`. * @param memorySegmentIDs Tensor with shape `[batchSize, memoryLength]`. * @return Tensor with shape `[batchSize, 1, queryLength, memoryLength]`. */ def attentionBiasSameSegment[T: TF : IsNumeric]( querySegmentIDs: Output[T], memorySegmentIDs: Output[T] ): Output[Float] = { tf.expandDims(tf.notEqual( tf.expandDims(querySegmentIDs, axis = 2), tf.expandDims(memorySegmentIDs, axis = 1) ).toFloat * -1e9f, axis = 1) } /** Creates a bias tensor to be added to the attention logits. * * @param padding Tensor with shape `[batchSize, length]`. * @param epsilon Bias value to the be added. * @return Bias tensor with shape `[batchSize, 1, 1, length]`. */ def attentionBiasIgnorePadding( padding: Output[Float], epsilon: Output[Float] = -1e9f ): Output[Float] = { tf.expandDims(tf.expandDims(padding * epsilon, axis = 1), axis = 1) } /** Creates a bias tensor to be added to the attention logits. * * @param attentionBias Tensor with shape `[batchSize, 1, 1, length]`. * @return Bias tensor with shape `[batchSize, length]`, with `1.0f` in padding positions and `0.0f` in non-padding * positions. */ def attentionBiasToPadding[T: TF : IsNumeric]( attentionBias: Output[T] ): Output[Boolean] = { // `attentionBias` is a large negative number in padding positions and zero elsewhere. tf.squeeze(tf.less(attentionBias, tf.constant[Int](-1).castTo[T]), axes = Seq(1, 2)) } /** Creates a bias tensor for self-attention, that encourages attention to close positions. * * @param length Integer scalar representing the sequence length. * @return Bias tensor with shape `[1, 1, length, length]`. */ def attentionBiasProximal( length: Output[Int] ): Output[Float] = { val r = tf.range(0, length).toFloat val diff = tf.expandDims(r, 0) - tf.expandDims(r, 1) tf.expandDims(tf.expandDims(-tf.log(1 + tf.abs(diff)), axis = 0), axis = 0) } /** Creates a bias tensor to be added to the attention logits. * * This bias prevents batches from attending to each other. * * @param conditionFn Function defining which type of mask to build that takes as input the difference * between `batchCoordinatesQ` and `batchCoordinatesK` and returns the bias mask. * @param batchCoordinatesQ Tensor with shape `[lengthQ, 1]`, containing the coordinates of the batches. * @param batchCoordinatesK Tensor with shape `[lengthQ, 1]`, containing the coordinates of the batches. * @return Tensor with shape `[lengthQ, lengthK]`, containing either `0` or `-infinity` (i.e., `-1e9f`). */ def attentionBiasBatch( conditionFn: Output[Int] => Output[Float], batchCoordinatesQ: Output[Int], batchCoordinatesK: Output[Int] ): Output[Float] = { val bcQ = tf.expandDims(tf.squeeze(batchCoordinatesQ, axes = Seq(1)), axis = 1) val bcK = tf.expandDims(tf.squeeze(batchCoordinatesK, axes = Seq(1)), axis = 0) // Broadcast to create a `[lengthQ, lengthK]` mask. conditionFn(bcK - bcQ) * -1e9f } /** Creates a bias tensor to be added to the attention logits. * * This bias prevents individual sequences of the same batch from attending to each other. * * @param batchCoordinatesQ Tensor with shape `[lengthQ, 1]`, containing the coordinates of the batches. * @param batchCoordinatesK Tensor with shape `[lengthQ, 1]`, containing the coordinates of the batches. * @return Tensor with shape `[lengthQ, lengthK]`, containing either `0` or `-infinity` (i.e., `-1e9f`). */ def attentionBiasCoordinates( batchCoordinatesQ: Output[Int], batchCoordinatesK: Output[Int] ): Output[Float] = { attentionBiasBatch( conditionFn = bias => tf.minimum(1.0f, tf.abs(bias.toFloat)), batchCoordinatesQ = batchCoordinatesQ, batchCoordinatesK = batchCoordinatesK) } /** Creates a bias tensor to be added to the attention logits. * * This bias prevents individual sequences of the same batch from attending to future values. * * @param batchCoordinatesQ Tensor with shape `[lengthQ, 1]`, containing the coordinates of the batches. * @param batchCoordinatesK Tensor with shape `[lengthQ, 1]`, containing the coordinates of the batches. * @return Tensor with shape `[lengthQ, lengthK]`, containing either `0` or `-infinity` (i.e., `-1e9f`). */ def attentionBiasFuture( batchCoordinatesQ: Output[Int], batchCoordinatesK: Output[Int] ): Output[Float] = { attentionBiasBatch( conditionFn = bias => tf.maximum(0.0f, tf.minimum(1.0f, tf.abs(bias))), batchCoordinatesQ = batchCoordinatesQ, batchCoordinatesK = batchCoordinatesK) } //endregion Attention Bias // TODO: encoderDecoderAttentionLoss //region Multi-Head Attention /** Splits the third dimension of `input` into multiple heads (becomes the second dimension). * * @param input Tensor with shape `[batchSize, length, depth]`. * @param numHeads Number of heads to split in. * @return Tensor with shape `[batchSize, numHeads, length, depth / numHeads]`. */ def splitHeads[T: TF]( input: Output[T], numHeads: Int ): Output[T] = { tf.transpose(Common.splitLastDimension(input, numHeads), Seq(0, 2, 1, 3)) } /** Splits the fourth dimension of `input` into multiple heads (becomes the second dimension). * * @param input Tensor with shape `[batchSize, height, width, depth]`. * @param numHeads Number of heads to split in. * @return Tensor with shape `[batchSize, numHeads, height, width, depth / numHeads]`. */ def splitHeads2D[T: TF]( input: Output[T], numHeads: Int ): Output[T] = { tf.transpose(Common.splitLastDimension(input, numHeads), Seq(0, 3, 1, 2, 4)) } /** Inverse of `splitHeads`. * * @param input Tensor with shape `[batchSize, numHeads, length, depth / numHeads]`. * @return Tensor with shape `[batchSize, length, depth]`. */ def combineHeads[T: TF](input: Output[T]): Output[T] = { Common.combineLastTwoDimensions(tf.transpose(input, Seq(0, 2, 1, 3))) } /** Inverse of `splitHeads2D`. * * @param input Tensor with shape `[batchSize, numHeads, height, width, depth / numHeads]`. * @return Tensor with shape `[batchSize, height, width, depth]`. */ def combineHeads2D[T: TF](input: Output[T]): Output[T] = { Common.combineLastTwoDimensions(tf.transpose(input, Seq(0, 2, 3, 1, 4))) } /** Computes the query, key, and value tensors, for attention models. * * @param queryAntecedent Tensor with shape `[batch, queryLength, depth]`. * @param memoryAntecedent Tensor with shape `[batch, memoryLength, depth]`. * @param totalKeysDepth Depth for the projected keys (and queries). * @param totalValuesDepth Depth for the projected values. * @param qNumFilters Integer specifying how wide we want the queries to be. * @param kvNumFilters Integer specifying how wide we want the keys and values to be. * @param qPaddingMode Convolution padding mode for the case when `qNumFilters > 1`. * @param kvPaddingMode Convolution padding mode for the case when `kvNumFilters > 1`. * @return Tuple containing the queries, keys, and values tensors. */ def computeQKV[T: TF : IsNotQuantized]( queryAntecedent: Output[T], memoryAntecedent: Output[T], totalKeysDepth: Int, totalValuesDepth: Int, qNumFilters: Int = 1, kvNumFilters: Int = 1, qPaddingMode: ConvPaddingMode = ValidConvPadding, kvPaddingMode: ConvPaddingMode = ValidConvPadding )(implicit context: ModelConstructionContext): (Output[T], Output[T], Output[T]) = { val q = computeAttentionComponent(queryAntecedent, totalKeysDepth, qNumFilters, qPaddingMode, "Q") val k = computeAttentionComponent(memoryAntecedent, totalKeysDepth, kvNumFilters, kvPaddingMode, "K") val v = computeAttentionComponent(memoryAntecedent, totalValuesDepth, kvNumFilters, kvPaddingMode, "V") (q, k, v) } def computeAttentionComponent[T: TF : IsNotQuantized]( input: Output[T], depth: Int, numFilters: Int = 1, paddingMode: ConvPaddingMode = ValidConvPadding, name: String = "AttentionComponent" )(implicit context: ModelConstructionContext): Output[T] = { tf.variableScope(name) { if (numFilters == 1) { val weights = context.parameterManager.get[T]( "Weights", Shape(input.shape(-1), depth)) tf.linear(input, weights) } else { ??? } } } /** Applies multi-head attention using input and output projections. * * '''NOTE:''' For decoder self-attention, (i.e. when `memoryAntecedent == queryAntecedent`, the caching assumes that * the bias contains future masking. Caching works by saving all the previous key and value values so that you are * able to send just the last query location to this attention function. I.e., if the cache is provided it assumes * that the query has shape `[batchSize, 1, outputDepth]` rather than the full sequence. * * @param queryAntecedent Tensor with shape `[batch, queryLength, depth]`. * @param memoryAntecedent Tensor with shape `[batch, memoryLength, depth]`. * @param bias Attention bias tensor. * @param totalKeysDepth Total depth for the projected keys (concatenated over all heads). * @param totalValuesDepth Total depth for the projected values (concatenated over all heads). * @param outputsDepth Depth for the projected outputs. * @param numHeads Number of heads to use. Must divide `totalKeyDepth` and `totalValueDepth`. * @param attention Attention model to use as the main building block of this multi-head attention wrapper. * @param qNumFilters Integer specifying how wide we want the queries to be. * @param kvNumFilters Integer specifying how wide we want the keys and values to be. * @param qPaddingMode Convolution padding mode for the case when `qNumFilters > 1`. * @param kvPaddingMode Convolution padding mode for the case when `kvNumFilters > 1`. * @param cache Optional cache containing the result of previous multi-head attentions. This is useful * for performing fast decoding. * @param name Name for the multi-head attention component that also specifies a variable scope. * @return Result of the attention transformation, with shape `[batchSize, queryLength, outputDepth]`, unless a cache * is provided, in which case only the last memory position is calculated and the output shape is * `[batchSize, 1, outputDepth]`. * @throws IllegalArgumentException If a cache is provided, but the attention model is not `DotProductAttention`, of * if a cache is provided, but no `bias` is provided. */ @throws[IllegalArgumentException] def multiHeadAttention[T: TF : IsHalfOrFloatOrDouble]( queryAntecedent: Output[T], memoryAntecedent: Option[Output[T]], bias: Output[T], totalKeysDepth: Int, totalValuesDepth: Int, outputsDepth: Int, numHeads: Int, attention: Attention, qNumFilters: Int = 1, kvNumFilters: Int = 1, qPaddingMode: ConvPaddingMode = ValidConvPadding, kvPaddingMode: ConvPaddingMode = ValidConvPadding, cache: Option[MultiHeadAttentionCache[T]] = None, name: String = "MultiHeadAttention" )(implicit context: ModelConstructionContext): (Output[T], Option[MultiHeadAttentionCache[T]]) = { require(totalKeysDepth % numHeads == 0, "`totalKeyDepth` must be divisible by `numHeads`.") require(totalValuesDepth % numHeads == 0, "`totalValueDepth` must be divisible by `numHeads`.") tf.variableScope(name) { val (q, k, v) = cache match { case None => var (q, k, v) = computeQKV( queryAntecedent = queryAntecedent, memoryAntecedent = memoryAntecedent.getOrElse(queryAntecedent), totalKeysDepth = totalKeysDepth, totalValuesDepth = totalValuesDepth, qNumFilters = qNumFilters, kvNumFilters = kvNumFilters, qPaddingMode = qPaddingMode, kvPaddingMode = kvPaddingMode) q = splitHeads(q, numHeads) k = splitHeads(k, numHeads) v = splitHeads(v, numHeads) (q, k, v) case Some(c) => require( attention.isInstanceOf[DotProductAttention], "Caching is not guaranteed to work with attention types other than 'DotProductAttention'.") require(bias != null, "Bias is required for caching.") memoryAntecedent match { case None => var (q, k, v) = computeQKV( queryAntecedent = queryAntecedent, memoryAntecedent = memoryAntecedent.getOrElse(queryAntecedent), totalKeysDepth = totalKeysDepth, totalValuesDepth = totalValuesDepth, qNumFilters = qNumFilters, kvNumFilters = kvNumFilters, qPaddingMode = qPaddingMode, kvPaddingMode = kvPaddingMode) q = splitHeads(q, numHeads) k = splitHeads(k, numHeads) v = splitHeads(v, numHeads) k = tf.concatenate(Seq(c.keys, k), axis = 2) v = tf.concatenate(Seq(c.values, v), axis = 2) (q, k, v) case Some(_) => var q = computeAttentionComponent(queryAntecedent, totalKeysDepth, qNumFilters, qPaddingMode, "Q") val k = c.keys val v = c.values q = splitHeads(q, numHeads) (q, k, v) } } val scaledQ = q * tf.pow( tf.constant[Int](totalKeysDepth / numHeads).toFloat, tf.constant[Float](-0.5f) ).castTo[T] var result = attention(scaledQ, k, v, Some(bias)) result = combineHeads(result) val w = context.parameterManager.get[T]( "OutputTransformWeights", Shape(result.shape(-1), outputsDepth)) (tf.linear(result, w), Some(MultiHeadAttentionCache(k, v))) } } case class MultiHeadAttentionCache[T]( keys: Output[T], values: Output[T]) //endregion Multi-Head Attention }
17,965
43.142506
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/helpers/Normalization.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer.helpers import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ trait Normalization { def apply[T: TF : IsNotQuantized]( input: Output[T], depth: Option[Int] = None, epsilon: Float = 1e-12f, name: String = "Normalization" )(implicit context: ModelConstructionContext): Output[T] } /** Applies no normalization to the input tensor. */ case object NoNormalization extends Normalization { override def apply[T: TF : IsNotQuantized]( input: Output[T], depth: Option[Int] = None, epsilon: Float = 1e-12f, name: String = "Normalization" )(implicit context: ModelConstructionContext): Output[T] = { input } } case class LayerNormalization(reuse: tf.VariableReuse = tf.ReuseOrCreateNewVariable) extends Normalization { override def apply[T: TF : IsNotQuantized]( input: Output[T], depth: Option[Int] = None, epsilon: Float = 1e-12f, name: String = "Normalization" )(implicit context: ModelConstructionContext): Output[T] = { val numFilters = depth.getOrElse(input.shape(-1)) tf.variableScope(name, reuse) { val scale = context.parameterManager.get[T]("Scale", Shape(numFilters), tf.OnesInitializer) val bias = context.parameterManager.get[T]("Bias", Shape(numFilters), tf.ZerosInitializer) val mean = tf.mean(input, axes = -1, keepDims = true) val variance = tf.mean(tf.square(input - mean), axes = -1, keepDims = true) val normalizedInput = (input - mean) * tf.rsqrt(variance + tf.constant[Float](epsilon).castTo[T]) normalizedInput * scale + bias } } } // TODO: !!! case object BatchNormalization extends Normalization { override def apply[T: TF : IsNotQuantized]( input: Output[T], depth: Option[Int] = None, epsilon: Float = 1e-12f, name: String = "Normalization" )(implicit context: ModelConstructionContext): Output[T] = { ??? } } case object NoamNormalization extends Normalization { override def apply[T: TF : IsNotQuantized]( input: Output[T], depth: Option[Int] = None, epsilon: Float = 1e-12f, name: String = "Normalization" )(implicit context: ModelConstructionContext): Output[T] = { tf.nameScope(name) { tf.l2Normalize(input, input.rank - 1, epsilon) * tf.sqrt(tf.constant[Float](input.shape(-1))).castTo[T] } } }
3,130
34.579545
109
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/helpers/PadRemover.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer.helpers import org.platanios.tensorflow.api._ import scala.language.postfixOps /** Helper to remove padding from a tensor before applying a computation to it. * * The padding is computed for one reference tensor containing the padding mask and can then be applied to any other * tensor with a compatible shape. * * @param padMask Reference padding tensor with shape `[batchSize, length]` or `[originAxisSize]` (where * `originAxisSize = batchSize * length`) containing non-zero positive values to indicate the padding * locations. * @param name Name for the created ops. * * @author Emmanouil Antonios Platanios */ case class PadRemover( padMask: Output[Float], name: String = "PadRemover" ) { /** `nonPadIndices` contains coordinates of zero rows (as `padMask` may be `FLOAT32`, checking zero equality is done * with `|x| < epsilon`, with `epsilon = 1e-9` as standard. Here padMask contains only positive values and so the * absolute value is not needed. */ val (nonPadIndices, originAxisSize) = { tf.nameScope(s"$name/Initialization") { val flattenedPadMask = padMask.reshape(Shape(-1)) (tf.where(flattenedPadMask < 1e-9f).toInt, tf.shape(flattenedPadMask).slice(0 :: 1)) } } /** Removes padding from the provided `value`. * * @param value Tensor with shape `[originAxisSize, ...]`. * @return Tensor with shape `[originAxisSizeCompressed, ...]`, where `originAxisSizeCompressed <= originAxisSize`. */ def remove( value: Output[Float] ): Output[Float] = { tf.nameScope(s"$name/Remove") { val valueShape = value.shape val result = tf.gatherND(value, nonPadIndices) result.setShape(Shape(-1) ++ valueShape(1 ::)) result } } /** Adds padding back to the provided `value`. * * @param value Tensor with shape `[originAxisSizeCompressed, ...]`, where * `originAxisSizeCompressed <= originAxisSize`. * @return Tensor with shape `[originAxisSize, ...]`. */ def restore( value: Output[Float] ): Output[Float] = { tf.nameScope(s"$name/Add") { tf.scatterND(nonPadIndices, value, tf.concatenate(Seq(originAxisSize, tf.shape(value).slice(1 ::)))) } } }
2,962
36.987179
118
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/helpers/LayerProcessor.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer.helpers import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.models.helpers.Common import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ trait LayerProcessor { @throws[IllegalArgumentException] def apply[T: TF : IsHalfOrFloatOrDouble]( value: Output[T], previousValue: Option[Output[T]], name: String = "LayerProcessor" )(implicit context: ModelConstructionContext): Output[T] } case object AddResidualConnection extends LayerProcessor { @throws[IllegalArgumentException] override def apply[T: TF : IsHalfOrFloatOrDouble]( value: Output[T], previousValue: Option[Output[T]], name: String = "AddResidualConnection" )(implicit context: ModelConstructionContext): Output[T] = { previousValue match { case Some(v) => value + v case None => throw new IllegalArgumentException( "No residual connection can be added when no previous value is provided.") } } } case class Normalize(normalization: Normalization, epsilon: Float = 1e-12f) extends LayerProcessor { @throws[IllegalArgumentException] override def apply[T: TF : IsHalfOrFloatOrDouble]( value: Output[T], previousValue: Option[Output[T]], name: String = "Normalize" )(implicit context: ModelConstructionContext): Output[T] = { normalization(value, epsilon = epsilon, name = name) } } case class Dropout( dropoutRate: Float, scaleOutput: Boolean = true, broadcastAxes: Set[Int] = Set.empty ) extends LayerProcessor { @throws[IllegalArgumentException] override def apply[T: TF : IsHalfOrFloatOrDouble]( value: Output[T], previousValue: Option[Output[T]], name: String = "Dropout" )(implicit context: ModelConstructionContext): Output[T] = { if (context.mode.isTraining) Common.dropoutWithBroadcastAxes(value, 1.0f - dropoutRate, scaleOutput, broadcastAxes) else value } } object LayerProcessor { /** Applies a sequence of functions to the input of a layer. * * @param input Layer input. * @param processors Layer processors to apply. * @return Processed layer input. */ def layerPreprocess[T: TF : IsHalfOrFloatOrDouble]( input: Output[T], processors: Seq[LayerProcessor] )(implicit context: ModelConstructionContext): Output[T] = { processors.foldLeft(input) { case (value, processor) => processor(value, None) } } /** Applies a sequence of functions to the output of a layer, potentially depending on its input. * * @param input Layer input. * @param output Layer output. * @param processors Layer processors to apply. * @return Processed layer output. */ def layerPostprocess[T: TF : IsHalfOrFloatOrDouble]( input: Output[T], output: Output[T], processors: Seq[LayerProcessor] )(implicit context: ModelConstructionContext): Output[T] = { processors.foldLeft(output) { case (value, processor) => processor(value, Some(input)) } } }
3,762
32.900901
100
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/transformer/helpers/FeedForwardLayer.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.transformer.helpers import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.models.helpers.Common import org.platanios.tensorflow.api._ import scala.language.postfixOps /** * @author Emmanouil Antonios Platanios */ trait FeedForwardLayer { def apply( input: Output[Float], padRemover: Option[PadRemover] )(implicit context: ModelConstructionContext): Output[Float] } class DenseReLUDenseFeedForwardLayer protected ( val filterSize: Int, val outputSize: Int, val reluDropoutRate: Float = 0.0f, val reluDropoutBroadcastAxes: Set[Int] = Set.empty, val name: String = "DenseReLUDense" ) extends FeedForwardLayer { override def apply( input: Output[Float], padRemover: Option[PadRemover] )(implicit context: ModelConstructionContext): Output[Float] = { val inputShape = tf.shape(input) val processedInput = padRemover.map(pr => { // Collapse `input` across examples. val collapsedShape = tf.concatenate[Int](Seq(Tensor(-1), inputShape(2 ::)), axis = 0) val collapsedInput = tf.reshape(input, collapsedShape) // Remove the padding positions. tf.expandDims(pr.remove(collapsedInput), axis = 0) }).getOrElse(input) val output = Common.denseReLUDense( processedInput, filterSize, outputSize, reluDropoutRate, reluDropoutBroadcastAxes, name) padRemover.map(pr => { // Restore `output` to the original shape of `input`, including padding. tf.reshape(pr.restore(tf.squeeze(output, axes = Seq(0))), inputShape) }).getOrElse(output) } } object DenseReLUDenseFeedForwardLayer { def apply( filterSize: Int, outputSize: Int, reluDropoutRate: Float = 0.0f, reluDropoutBroadcastAxes: Set[Int] = Set.empty, name: String = "DenseReLUDense" ): DenseReLUDenseFeedForwardLayer = { new DenseReLUDenseFeedForwardLayer(filterSize, outputSize, reluDropoutRate, reluDropoutBroadcastAxes, name) } }
2,669
35.081081
111
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/PairwiseManager.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.models.{ModelConstructionContext, parameters} import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ class PairwiseManager protected ( override val wordEmbeddingsType: WordEmbeddingsType, override val variableInitializer: tf.VariableInitializer = null ) extends ParameterManager(wordEmbeddingsType, variableInitializer) { override def get[P: TF]( name: String, shape: Shape, variableInitializer: tf.VariableInitializer = variableInitializer, variableReuse: tf.VariableReuse = tf.ReuseOrCreateNewVariable )(implicit context: ModelConstructionContext): Output[P] = { tf.variableScope("ParameterManager") { val graph = currentGraph // Determine all the language index pairs that are relevant given the current model configuration. val languageIndexPairs = parameters.languageIndexPairs(context.languages.map(_._1), context.trainingConfig) val languagePairs = languageIndexPairs.map(p => (context.languages(p._1)._1, context.languages(p._2)._1)) val languageIdPairs = languageIndexPairs.map(p => (languageIds(graph)(p._1), languageIds(graph)(p._2))) // Obtain the variable values for all language pairs. val variableValues = languagePairs.map(pair => { tf.variable[P]( s"$name/${pair._1.abbreviation}-${pair._2.abbreviation}", shape, initializer = variableInitializer, reuse = variableReuse).value }) // Choose the variable for the current language pair. tf.nameScope(name) { val predicates = variableValues.zip(languageIdPairs).map { case (v, (srcLangId, tgtLangId)) => (tf.logicalAnd( tf.equal(context.srcLanguageID, srcLangId), tf.equal(context.tgtLanguageID, tgtLangId)), () => v) } val assertion = tf.assert( tf.any(tf.stack(predicates.map(_._1))), Seq( Output[String]("No variables found for the provided language pair."), Output[String]("Context source language: "), context.srcLanguageID, Output[String]("Context target language: "), context.tgtLanguageID)) val default = () => tf.createWith(controlDependencies = Set(assertion)) { tf.identity(variableValues.head) } tf.cases(predicates, default) } } } } object PairwiseManager { def apply( wordEmbeddingsType: WordEmbeddingsType, variableInitializer: tf.VariableInitializer = null ): PairwiseManager = { new PairwiseManager(wordEmbeddingsType, variableInitializer) } }
3,310
40.3875
113
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/SharedWordEmbeddings.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.config.TrainingConfig import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import scala.collection.mutable /** * @author Emmanouil Antonios Platanios */ case class SharedWordEmbeddings(embeddingsSize: Int) extends WordEmbeddingsType { override type T = Variable[Float] override def createStringToIndexLookupTable( languages: Seq[(Language, Vocabulary)] ): Output[Resource] = { languages.head._2.stringToIndexLookupTable(name = "SharedStringToIndexLookupTable").handle } override def createIndexToStringLookupTable( languages: Seq[(Language, Vocabulary)] ): Output[Resource] = { languages.head._2.indexToStringLookupTable(name = "SharedIndexToStringLookupTable").handle } override def createWordEmbeddings( languages: Seq[(Language, Vocabulary)], trainingConfig: TrainingConfig ): Variable[Float] = { val someLanguage = languages.head tf.variable[Float]( name = languages.map(_._1.name).mkString(""), shape = Shape(someLanguage._2.size, embeddingsSize), initializer = tf.RandomUniformInitializer(-0.1f, 0.1f)) } override def lookupTable( lookupTable: Output[Resource], languageId: Output[Int] ): Output[Resource] = { lookupTable } override def embeddingsTable( embeddingTables: Variable[Float], languageIds: Seq[Output[Int]], languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { embeddingTables } override def embeddings( embeddingTables: Variable[Float], languageIds: Seq[Output[Int]], languageId: Output[Int], tokenIndices: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { embeddingTables.gather(tokenIndices) } override def projectionToWords( languageIds: Seq[Output[Int]], projectionsToWords: mutable.Map[Int, Variable[Float]], inputSize: Int, languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { projectionsToWords .getOrElseUpdate(inputSize, { val weightsInitializer = tf.RandomUniformInitializer(-0.1f, 0.1f) val someLanguage = context.languages.head tf.variable[Float]( s"${someLanguage._1.name}/OutWeights", Shape(inputSize, someLanguage._2.size), weightsInitializer) }).value } }
3,237
33.084211
94
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/package.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.config.TrainingConfig /** * @author Emmanouil Antonios Platanios */ package object parameters { /** Determines all language index pairs that are relevant given the current model configuration. */ def languageIndexPairs( languages: Seq[Language], trainingConfig: TrainingConfig ): Seq[(Int, Int)] = { if (trainingConfig.languagePairs.nonEmpty) { trainingConfig.languagePairs.toSeq.map(pair => { (languages.indexOf(pair._1), languages.indexOf(pair._2)) }) } else { languages.indices .combinations(2) .map(c => (c(0), c(1))) .flatMap(p => Seq(p, (p._2, p._1))) .toSeq } } }
1,427
32.209302
101
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/LanguageEmbeddingsPairManager.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.config.TrainingConfig import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import scala.collection.mutable // TODO: Add support for an optional language embeddings merge layer. /** * @author Emmanouil Antonios Platanios */ class LanguageEmbeddingsPairManager protected ( val languageEmbeddingsSize: Int, override val wordEmbeddingsType: WordEmbeddingsType, val hiddenLayers: Seq[Int] = Seq.empty, override val variableInitializer: tf.VariableInitializer = null ) extends ParameterManager(wordEmbeddingsType, variableInitializer) { protected val languageEmbeddings: mutable.Map[Graph, Output[Float]] = mutable.Map.empty protected val parameters : mutable.Map[Graph, mutable.Map[String, Output[Any]]] = mutable.Map.empty override protected def removeGraph(graph: Graph): Unit = { super.removeGraph(graph) languageEmbeddings -= graph parameters -= graph } override def initialize( languages: Seq[(Language, Vocabulary)], trainingConfig: TrainingConfig ): Unit = { tf.variableScope("ParameterManager") { super.initialize(languages, trainingConfig) val graph = currentGraph if (!languageEmbeddings.contains(graph)) { languageEmbeddings += graph -> { val embeddingsInitializer = tf.RandomUniformInitializer(-0.1f, 0.1f) tf.variable[Float]( "LanguageEmbeddings", Shape(languages.length, languageEmbeddingsSize), initializer = embeddingsInitializer).value } } } } override def get[P: TF]( name: String, shape: Shape, variableInitializer: tf.VariableInitializer = variableInitializer, variableReuse: tf.VariableReuse = tf.ReuseOrCreateNewVariable )(implicit context: ModelConstructionContext): Output[P] = { tf.variableScope("ParameterManager") { val graph = currentGraph val variableScopeName = tf.currentVariableScope.name val fullName = if (variableScopeName != null && variableScopeName != "") s"$variableScopeName/$name" else name def create(): Output[P] = { tf.variableScope(name) { val languagePair = tf.stack(Seq(context.srcLanguageID, context.tgtLanguageID)) val embeddings = languageEmbeddings(graph).gather(languagePair).reshape(Shape(1, -1)) var inputSize = 2 * languageEmbeddingsSize var parameters = embeddings hiddenLayers.zipWithIndex.foreach(numUnits => { val weights = tf.variable[Float](s"Dense${numUnits._2}/Weights", Shape(inputSize, numUnits._1)) val bias = tf.variable[Float](s"Dense${numUnits._2}/Bias", Shape(numUnits._1)) inputSize = numUnits._1 parameters = tf.addBias(tf.matmul(parameters, weights), bias) }) val weights = tf.variable[Float]("Dense/Weights", Shape(inputSize, shape.numElements.toInt)) val bias = tf.variable[Float]("Dense/Bias", Shape(shape.numElements.toInt)) parameters = tf.addBias(tf.matmul(parameters, weights), bias) parameters.castTo[P].reshape(shape) } } variableReuse match { case tf.ReuseExistingVariableOnly => parameters.getOrElseUpdate(graph, mutable.Map.empty)(fullName).asInstanceOf[Output[P]] case tf.CreateNewVariableOnly => // TODO: Kind of hacky. val created = create() parameters.getOrElseUpdate(graph, mutable.Map.empty) += created.op.input.head.name -> created created case tf.ReuseOrCreateNewVariable => parameters .getOrElseUpdate(graph, mutable.Map.empty) .getOrElseUpdate(fullName, create()) .asInstanceOf[Output[P]] } } } } object LanguageEmbeddingsPairManager { def apply( languageEmbeddingsSize: Int, wordEmbeddingsType: WordEmbeddingsType, hiddenLayers: Seq[Int] = Seq.empty, variableInitializer: tf.VariableInitializer = null ): LanguageEmbeddingsPairManager = { new LanguageEmbeddingsPairManager( languageEmbeddingsSize, wordEmbeddingsType, hiddenLayers, variableInitializer) } }
5,030
38.928571
116
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/ParameterManager.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.config.TrainingConfig import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.models._ import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import org.platanios.tensorflow.api.core.exception.InvalidDataTypeException import org.platanios.tensorflow.api.ops.FunctionGraph import scala.collection.mutable /** * @author Emmanouil Antonios Platanios */ class ParameterManager protected ( val wordEmbeddingsType: WordEmbeddingsType, val variableInitializer: tf.VariableInitializer = null ) { protected var languages: Seq[(Language, Vocabulary)] = _ protected val languageIds : mutable.Map[Graph, Seq[Output[Int]]] = mutable.Map.empty protected val stringToIndexLookupTables : mutable.Map[Graph, Output[Resource]] = mutable.Map.empty protected val stringToIndexLookupDefaults: mutable.Map[Graph, Output[Long]] = mutable.Map.empty protected val indexToStringLookupTables : mutable.Map[Graph, Output[Resource]] = mutable.Map.empty protected val indexToStringLookupDefaults: mutable.Map[Graph, Output[String]] = mutable.Map.empty protected val wordEmbeddings : mutable.Map[Graph, wordEmbeddingsType.T] = mutable.Map.empty protected val projectionsToWords: mutable.Map[Graph, mutable.Map[Int, wordEmbeddingsType.T]] = mutable.Map.empty protected def currentGraph: Graph = { var graph = tf.currentGraph while (graph.isInstanceOf[FunctionGraph]) graph = graph.asInstanceOf[FunctionGraph].outerGraph graph } protected def removeGraph(graph: Graph): Unit = { languageIds -= graph stringToIndexLookupTables -= graph stringToIndexLookupDefaults -= graph indexToStringLookupTables -= graph indexToStringLookupDefaults -= graph wordEmbeddings -= graph projectionsToWords -= graph } def initialize( languages: Seq[(Language, Vocabulary)], trainingConfig: TrainingConfig ): Unit = { tf.variableScope("ParameterManager") { languageIds.keys.filter(_.isClosed).foreach(removeGraph) this.languages = languages val graph = currentGraph if (!languageIds.contains(graph)) { languageIds += graph -> tf.nameScope("LanguageIDs") { languages.map(_._1).zipWithIndex.map(l => tf.constant(l._2, name = l._1.name)) } tf.variableScope("StringToIndexLookupTables") { stringToIndexLookupTables += graph -> wordEmbeddingsType.createStringToIndexLookupTable(languages) stringToIndexLookupDefaults += graph -> tf.constant(Vocabulary.UNKNOWN_TOKEN_ID.toLong, name = "Default") } tf.variableScope("IndexToStringLookupTables") { indexToStringLookupTables += graph -> wordEmbeddingsType.createIndexToStringLookupTable(languages) indexToStringLookupDefaults += graph -> tf.constant(Vocabulary.UNKNOWN_TOKEN, name = "Default") } wordEmbeddings += graph -> tf.variableScope("WordEmbeddings") { wordEmbeddingsType.createWordEmbeddings(languages, trainingConfig) } } } } def languageId(index: Int): Output[Int] = { languageIds(currentGraph)(index) } def stringToIndexLookup(languageId: Output[Int]): Output[String] => Output[Int] = { keys: Output[String] => { tf.variableScope("ParameterManager/StringToIndexLookupTables") { val graph = currentGraph val handle = wordEmbeddingsType.lookupTable(stringToIndexLookupTables(graph), languageId) ParameterManager.lookup( handle = handle, keys = keys, defaultValue = stringToIndexLookupDefaults(graph)).toInt } } } def indexToStringLookup(languageId: Output[Int]): Output[Int] => Output[String] = { keys: Output[Int] => { tf.variableScope("ParameterManager/IndexToStringLookupTables") { val graph = currentGraph val handle = wordEmbeddingsType.lookupTable(indexToStringLookupTables(graph), languageId) ParameterManager.lookup( handle = handle, keys = keys.toLong, defaultValue = indexToStringLookupDefaults(graph)) } } } def wordEmbeddingsTable( languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { tf.variableScope("ParameterManager/WordEmbeddings") { val graph = currentGraph wordEmbeddingsType.embeddingsTable(wordEmbeddings(graph), languageIds(graph), languageId) } } def wordEmbeddings( languageId: Output[Int], tokenIndices: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { tf.variableScope("ParameterManager/WordEmbeddings") { val graph = currentGraph wordEmbeddingsType.embeddings(wordEmbeddings(graph), languageIds(graph), languageId, tokenIndices) } } def get[P: TF]( name: String, shape: Shape, variableInitializer: tf.VariableInitializer = variableInitializer, variableReuse: tf.VariableReuse = tf.ReuseOrCreateNewVariable )(implicit context: ModelConstructionContext): Output[P] = { tf.variableScope("ParameterManager") { tf.variable[P](name, shape, initializer = variableInitializer, reuse = variableReuse).value } } def getProjectionToWords( inputSize: Int, languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { tf.variableScope("ParameterManager/ProjectionToWords") { val graph = currentGraph wordEmbeddingsType.projectionToWords( languageIds(graph), projectionsToWords.getOrElseUpdate(graph, mutable.HashMap.empty), inputSize, languageId) } } def postprocessEmbeddedSequences( sequences: Sequences[Float] )(implicit context: ModelConstructionContext): Sequences[Float] = { sequences } } object ParameterManager { def apply( wordEmbeddingsType: WordEmbeddingsType, variableInitializer: tf.VariableInitializer = null ): ParameterManager = { new ParameterManager(wordEmbeddingsType, variableInitializer) } /** Creates an op that looks up the provided keys in the lookup table referred to by `handle` and returns the * corresponding values. * * @param handle `RESOURCE` tensor containing a handle to the lookup table. * @param keys Tensor containing the keys to look up. * @param name Name for the created op. * @return Created op output. * @throws InvalidDataTypeException If the provided keys data types does not match the keys data type of this table. */ @throws[InvalidDataTypeException] private[ParameterManager] def lookup[K, V]( handle: Output[Resource], keys: Output[K], defaultValue: Output[V], name: String = "Lookup" ): Output[V] = { tf.nameScope(name) { val values = Op.Builder[(Output[Resource], Output[K], Output[V]), Output[V]]( opType = "LookupTableFindV2", name = name, input = (handle, keys, defaultValue) ).build().output values.setShape(keys.shape) values } } }
7,819
36.416268
119
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/WordEmbeddingsType.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.config.TrainingConfig import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import scala.collection.mutable /** * @author Emmanouil Antonios Platanios */ trait WordEmbeddingsType { type T val embeddingsSize: Int def createStringToIndexLookupTable( languages: Seq[(Language, Vocabulary)] ): Output[Resource] def createIndexToStringLookupTable( languages: Seq[(Language, Vocabulary)] ): Output[Resource] def createWordEmbeddings( languages: Seq[(Language, Vocabulary)], trainingConfig: TrainingConfig ): T def lookupTable( lookupTable: Output[Resource], languageId: Output[Int] ): Output[Resource] def embeddingsTable( embeddingTables: T, languageIds: Seq[Output[Int]], languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] def embeddings( embeddingTables: T, languageIds: Seq[Output[Int]], languageId: Output[Int], tokenIndices: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] def projectionToWords( languageIds: Seq[Output[Int]], projectionsToWords: mutable.Map[Int, T], inputSize: Int, languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] }
2,146
28.819444
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/GoogleMultilingualManager.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.config.TrainingConfig import org.platanios.symphony.mt.models.{ModelConstructionContext, Sequences} import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import scala.collection.mutable /** * @author Emmanouil Antonios Platanios */ class GoogleMultilingualManager protected ( override val wordEmbeddingsType: WordEmbeddingsType, override val variableInitializer: tf.VariableInitializer = null ) extends ParameterManager(wordEmbeddingsType, variableInitializer) { protected val languageEmbeddings: mutable.Map[Graph, Output[Float]] = mutable.Map.empty protected val parameters : mutable.Map[Graph, mutable.Map[String, Output[Any]]] = mutable.Map.empty override protected def removeGraph(graph: Graph): Unit = { super.removeGraph(graph) languageEmbeddings -= graph parameters -= graph } override def initialize( languages: Seq[(Language, Vocabulary)], trainingConfig: TrainingConfig ): Unit = { tf.variableScope("ParameterManager") { super.initialize(languages, trainingConfig) val graph = currentGraph if (!languageEmbeddings.contains(graph)) { languageEmbeddings += graph -> { val embeddingsInitializer = tf.RandomUniformInitializer(-0.1f, 0.1f) tf.variable[Float]( "LanguageEmbeddings", Shape(languages.length, wordEmbeddingsType.embeddingsSize), initializer = embeddingsInitializer).value } } } } override def postprocessEmbeddedSequences( sequences: Sequences[Float] )(implicit context: ModelConstructionContext): Sequences[Float] = { val batchSize = tf.shape(sequences.sequences).slice(0).toInt val tgtLanguageEmbedding = languageEmbeddings(currentGraph).gather(context.tgtLanguageID).reshape(Shape(1, 1, -1)) val tgtLanguageEmbeddingTiled = tf.tile(tgtLanguageEmbedding, tf.stack[Int](Seq(batchSize, 1, 1))) val processedSrcSentences = tf.concatenate(Seq(tgtLanguageEmbeddingTiled, sequences.sequences), 1) val processedSrcSentenceLengths = sequences.lengths + 1 Sequences(processedSrcSentences, processedSrcSentenceLengths) } } object GoogleMultilingualManager { def apply( wordEmbeddingsType: WordEmbeddingsType, variableInitializer: tf.VariableInitializer = null ): GoogleMultilingualManager = { new GoogleMultilingualManager(wordEmbeddingsType, variableInitializer) } }
3,214
39.1875
118
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/LanguageEmbeddingsManager.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.config.TrainingConfig import org.platanios.symphony.mt.models._ import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import scala.collection.mutable /** * @author Emmanouil Antonios Platanios */ class LanguageEmbeddingsManager protected ( val languageEmbeddingsSize: Int, override val wordEmbeddingsType: WordEmbeddingsType, val hiddenLayers: Seq[Int] = Seq.empty, override val variableInitializer: tf.VariableInitializer = null ) extends ParameterManager(wordEmbeddingsType, variableInitializer) { protected val languageEmbeddings: mutable.Map[Graph, Output[Float]] = mutable.Map.empty protected val parameters : mutable.Map[Graph, mutable.Map[String, Output[Any]]] = mutable.Map.empty override protected def removeGraph(graph: Graph): Unit = { super.removeGraph(graph) languageEmbeddings -= graph parameters -= graph } override def initialize( languages: Seq[(Language, Vocabulary)], trainingConfig: TrainingConfig ): Unit = { tf.variableScope("ParameterManager") { super.initialize(languages, trainingConfig) val graph = currentGraph if (!languageEmbeddings.contains(graph)) { languageEmbeddings += graph -> { val embeddingsInitializer = tf.RandomUniformInitializer(-0.1f, 0.1f) tf.variable[Float]( "LanguageEmbeddings", Shape(languages.length, languageEmbeddingsSize), initializer = embeddingsInitializer).value } } } } override def get[P: TF]( name: String, shape: Shape, variableInitializer: tf.VariableInitializer = variableInitializer, variableReuse: tf.VariableReuse = tf.ReuseOrCreateNewVariable )(implicit context: ModelConstructionContext): Output[P] = { tf.variableScope("ParameterManager") { val graph = currentGraph val variableScopeName = tf.currentVariableScope.name val fullName = if (variableScopeName != null && variableScopeName != "") s"$variableScopeName/$name" else name def create(): Output[P] = { tf.variableScope(name) { val language = context.stage match { case Encoding => context.srcLanguageID case Decoding => context.tgtLanguageID } val embedding = languageEmbeddings(graph).gather(language).reshape(Shape(1, -1)) var inputSize = languageEmbeddingsSize var parameters = embedding hiddenLayers.zipWithIndex.foreach(numUnits => { val weights = tf.variable[Float](s"Dense${numUnits._2}/Weights", Shape(inputSize, numUnits._1)) val bias = tf.variable[Float](s"Dense${numUnits._2}/Bias", Shape(numUnits._1)) inputSize = numUnits._1 parameters = tf.addBias(tf.matmul(parameters, weights), bias) }) val weights = tf.variable[Float]("Dense/Weights", Shape(inputSize, shape.numElements.toInt)) val bias = tf.variable[Float]("Dense/Bias", Shape(shape.numElements.toInt)) parameters = tf.addBias(tf.matmul(parameters, weights), bias) parameters.castTo[P].reshape(shape) } } variableReuse match { case tf.ReuseExistingVariableOnly => parameters.getOrElseUpdate(graph, mutable.Map.empty)(fullName).asInstanceOf[Output[P]] case tf.CreateNewVariableOnly => // TODO: Kind of hacky. val created = create() parameters.getOrElseUpdate(graph, mutable.Map.empty) += created.op.input.head.name -> created created case tf.ReuseOrCreateNewVariable => parameters .getOrElseUpdate(graph, mutable.Map.empty) .getOrElseUpdate(fullName, create()) .asInstanceOf[Output[P]] } } } } object LanguageEmbeddingsManager { def apply( languageEmbeddingsSize: Int, wordEmbeddingsType: WordEmbeddingsType, hiddenLayers: Seq[Int] = Seq.empty, variableInitializer: tf.VariableInitializer = null ): LanguageEmbeddingsManager = { new LanguageEmbeddingsManager( languageEmbeddingsSize, wordEmbeddingsType, hiddenLayers, variableInitializer) } }
4,982
38.23622
116
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/WordEmbeddingsPerLanguagePair.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.config.TrainingConfig import org.platanios.symphony.mt.models.{ModelConstructionContext, parameters} import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import scala.collection.mutable /** * @author Emmanouil Antonios Platanios */ case class WordEmbeddingsPerLanguagePair(embeddingsSize: Int) extends WordEmbeddingsType { override type T = Seq[WordEmbeddingsPerLanguagePair.EmbeddingsPair] override def createStringToIndexLookupTable( languages: Seq[(Language, Vocabulary)] ): Output[Resource] = { val tables = languages.map(l => l._2.stringToIndexLookupTable(name = l._1.name)) tf.stack(tables.map(_.handle)) } override def createIndexToStringLookupTable( languages: Seq[(Language, Vocabulary)] ): Output[Resource] = { val tables = languages.map(l => l._2.indexToStringLookupTable(name = l._1.name)) tf.stack(tables.map(_.handle)) } override def createWordEmbeddings( languages: Seq[(Language, Vocabulary)], trainingConfig: TrainingConfig ): T = { // Determine all the language index pairs that are relevant given the current model configuration. val languageIndexPairs = parameters.languageIndexPairs(languages.map(_._1), trainingConfig) val languagePairs = languageIndexPairs.map(p => (languages(p._1), languages(p._2))) // Create separate word embeddings for each language pair. languagePairs.map(pair => tf.variableScope(s"${pair._1._1.abbreviation}-${pair._2._1.abbreviation}") { WordEmbeddingsPerLanguagePair.EmbeddingsPair( embeddings1 = tf.variable[Float]( name = pair._1._1.name, shape = Shape(pair._1._2.size, embeddingsSize), initializer = tf.RandomUniformInitializer(-0.1f, 0.1f)), embeddings2 = tf.variable[Float]( name = pair._2._1.name, shape = Shape(pair._2._2.size, embeddingsSize), initializer = tf.RandomUniformInitializer(-0.1f, 0.1f))) }) } override def lookupTable( lookupTable: Output[Resource], languageId: Output[Int] ): Output[Resource] = { lookupTable.gather(languageId) } override def embeddingsTable( embeddingTables: Seq[WordEmbeddingsPerLanguagePair.EmbeddingsPair], languageIds: Seq[Output[Int]], languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { // Determine all the language index pairs that are relevant given the current model configuration. val languageIndexPairs = parameters.languageIndexPairs(context.languages.map(_._1), context.trainingConfig) val languageIdPairs = languageIndexPairs.map(p => (languageIds(p._1), languageIds(p._2))) // Perform a separate word embedding lookup for each language pair. val predicates = embeddingTables.zip(languageIdPairs).flatMap { case (embeddings, (srcLangId, tgtLangId)) => val pairPredicate = tf.logicalAnd( tf.equal(context.srcLanguageID, srcLangId), tf.equal(context.tgtLanguageID, tgtLangId)) Seq( (tf.logicalAnd(pairPredicate, tf.equal(srcLangId, languageId)), () => embeddings.embeddings1.value), (tf.logicalAnd(pairPredicate, tf.equal(tgtLangId, languageId)), () => embeddings.embeddings2.value)) } val assertion = tf.assert( tf.any(tf.stack(predicates.map(_._1))), Seq( tf.constant[String]("No word embeddings table found for the provided language pair."), tf.constant[String]("Context source language: "), context.srcLanguageID, tf.constant[String]("Context target language: "), context.tgtLanguageID, tf.constant[String]("Current language: "), languageId)) val default = () => tf.createWith(controlDependencies = Set(assertion)) { tf.identity(embeddingTables.head.embeddings1.value) } tf.cases(predicates, default) } override def embeddings( embeddingTables: Seq[WordEmbeddingsPerLanguagePair.EmbeddingsPair], languageIds: Seq[Output[Int]], languageId: Output[Int], tokenIndices: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { // Determine all the language index pairs that are relevant given the current model configuration. val languageIndexPairs = parameters.languageIndexPairs(context.languages.map(_._1), context.trainingConfig) val languageIdPairs = languageIndexPairs.map(p => (languageIds(p._1), languageIds(p._2))) // Perform a separate word embedding lookup for each language pair. val predicates = embeddingTables.zip(languageIdPairs).flatMap { case (embeddings, (srcLangId, tgtLangId)) => val pairPredicate = tf.logicalAnd( tf.equal(context.srcLanguageID, srcLangId), tf.equal(context.tgtLanguageID, tgtLangId)) Seq( (tf.logicalAnd(pairPredicate, tf.equal(srcLangId, languageId)), () => embeddings.embeddings1.gather(tokenIndices)), (tf.logicalAnd(pairPredicate, tf.equal(tgtLangId, languageId)), () => embeddings.embeddings2.gather(tokenIndices))) } val assertion = tf.assert( tf.any(tf.stack(predicates.map(_._1))), Seq( tf.constant[String]("No word embeddings table found for the provided language pair."), tf.constant[String]("Context source language: "), context.srcLanguageID, tf.constant[String]("Context target language: "), context.tgtLanguageID, tf.constant[String]("Current language: "), languageId)) val default = () => tf.createWith(controlDependencies = Set(assertion)) { tf.identity(embeddingTables.head.embeddings1.gather(tokenIndices)) } tf.cases(predicates, default) } override def projectionToWords( languageIds: Seq[Output[Int]], projectionsToWords: mutable.Map[Int, T], inputSize: Int, languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { // Determine all the language index pairs that are relevant given the current model configuration. val languageIndexPairs = parameters.languageIndexPairs(context.languages.map(_._1), context.trainingConfig) val projectionsForSize = projectionsToWords .getOrElseUpdate(inputSize, { val languagePairs = languageIndexPairs.map(p => (context.languages(p._1), context.languages(p._2))) languagePairs.map(pair => tf.variableScope(s"${pair._1._1.abbreviation}-${pair._2._1.abbreviation}") { WordEmbeddingsPerLanguagePair.EmbeddingsPair( embeddings1 = tf.variable[Float]( name = s"${pair._1._1.name}/OutWeights", shape = Shape(inputSize, pair._1._2.size), initializer = tf.RandomUniformInitializer(-0.1f, 0.1f)), embeddings2 = tf.variable[Float]( name = s"${pair._2._1.name}/OutWeights", shape = Shape(inputSize, pair._2._2.size), initializer = tf.RandomUniformInitializer(-0.1f, 0.1f))) }) }) val languageIdPairs = languageIndexPairs.map(p => (languageIds(p._1), languageIds(p._2))) val predicates = projectionsForSize.zip(languageIdPairs).flatMap { case (projections, (srcLangId, tgtLangId)) => val pairPredicate = tf.logicalAnd( tf.equal(context.srcLanguageID, srcLangId), tf.equal(context.tgtLanguageID, tgtLangId)) Seq( (tf.logicalAnd(pairPredicate, tf.equal(srcLangId, languageId)), () => projections.embeddings1.value), (tf.logicalAnd(pairPredicate, tf.equal(tgtLangId, languageId)), () => projections.embeddings2.value)) } val assertion = tf.assert( tf.any(tf.stack(predicates.map(_._1))), Seq( tf.constant[String]("No projections found for the provided language pair."), tf.constant[String]("Context source language: "), context.srcLanguageID, tf.constant[String]("Context target language: "), context.tgtLanguageID, tf.constant[String]("Current language: "), languageId)) val default = () => tf.createWith(controlDependencies = Set(assertion)) { tf.identity(projectionsForSize.head.embeddings1.value) } tf.cases(predicates, default) } } object WordEmbeddingsPerLanguagePair { case class EmbeddingsPair( embeddings1: Variable[Float], embeddings2: Variable[Float]) private[WordEmbeddingsPerLanguagePair] def languagePairIdsToId( numLanguages: Int, srcLanguageId: Output[Int], tgtLanguageId: Output[Int] ): Output[Int] = { srcLanguageId * (numLanguages - 1) + tgtLanguageId - tf.less(srcLanguageId, tgtLanguageId).toInt } }
9,376
44.965686
125
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/models/parameters/WordEmbeddingsPerLanguage.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.models.parameters import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.config.TrainingConfig import org.platanios.symphony.mt.models.ModelConstructionContext import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ import scala.collection.mutable /** * @author Emmanouil Antonios Platanios */ case class WordEmbeddingsPerLanguage(embeddingsSize: Int) extends WordEmbeddingsType { override type T = Seq[Variable[Float]] override def createStringToIndexLookupTable( languages: Seq[(Language, Vocabulary)] ): Output[Resource] = { val tables = languages.map(l => l._2.stringToIndexLookupTable(name = l._1.name)) tf.stack(tables.map(_.handle)) } override def createIndexToStringLookupTable( languages: Seq[(Language, Vocabulary)] ): Output[Resource] = { val tables = languages.map(l => l._2.indexToStringLookupTable(name = l._1.name)) tf.stack(tables.map(_.handle)) } override def createWordEmbeddings( languages: Seq[(Language, Vocabulary)], trainingConfig: TrainingConfig ): T = { val embeddingsInitializer = tf.RandomUniformInitializer(-0.1f, 0.1f) languages.map(l => { tf.variable[Float](l._1.name, Shape(l._2.size, embeddingsSize), embeddingsInitializer) }) } override def lookupTable( lookupTable: Output[Resource], languageId: Output[Int] ): Output[Resource] = { lookupTable.gather(languageId) } override def embeddingsTable( embeddingTables: Seq[Variable[Float]], languageIds: Seq[Output[Int]], languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { val predicates = embeddingTables.zip(languageIds).map { case (embeddings, langId) => (tf.equal(languageId, langId), () => embeddings.value) } val assertion = tf.assert( tf.any(tf.stack(predicates.map(_._1))), Seq[Output[Any]]( tf.constant[String]("No word embeddings table found for the provided language."), tf.constant[String]("Current language: "), languageId)) val default = () => tf.createWith(controlDependencies = Set(assertion)) { tf.identity(embeddingTables.head.value) } tf.cases(predicates, default) } override def embeddings( embeddingTables: Seq[Variable[Float]], languageIds: Seq[Output[Int]], languageId: Output[Int], tokenIndices: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { val predicates = embeddingTables.zip(languageIds).map { case (embeddings, langId) => (tf.equal(languageId, langId), () => embeddings.gather(tokenIndices)) } val assertion = tf.assert( tf.any(tf.stack(predicates.map(_._1))), Seq[Output[Any]]( tf.constant[String]("No word embeddings table found for the provided language."), tf.constant[String]("Current language: "), languageId)) val default = () => tf.createWith(controlDependencies = Set(assertion)) { tf.identity(embeddingTables.head.gather(tokenIndices)) } tf.cases(predicates, default) } override def projectionToWords( languageIds: Seq[Output[Int]], projectionsToWords: mutable.Map[Int, Seq[Variable[Float]]], inputSize: Int, languageId: Output[Int] )(implicit context: ModelConstructionContext): Output[Float] = { val projectionsForSize = projectionsToWords .getOrElseUpdate(inputSize, { context.languages.map(l => { tf.variable[Float]( name = s"${l._1.name}/OutWeights", shape = Shape(inputSize, l._2.size), initializer = tf.RandomUniformInitializer(-0.1f, 0.1f)) }) }) val predicates = projectionsForSize.zip(languageIds).map { case (projections, langId) => (tf.equal(languageId, langId), () => projections.value) } val assertion = tf.assert( tf.any(tf.stack(predicates.map(_._1))), Seq[Output[Any]]( tf.constant[String]("No projections found for the provided language."), tf.constant[String]("Current language: "), languageId)) val default = () => tf.createWith(controlDependencies = Set(assertion)) { tf.identity(projectionsForSize.head.value) } tf.cases(predicates, default) } }
4,972
36.674242
104
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/utilities/TopologicalSort.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.utilities /** * @author Emmanouil Antonios Platanios */ object TopologicalSort { def sort[T](values: Set[T], requirements: T => Set[T]): Option[Seq[T]] = { // Collect all values by following the dependencies formed by their requirements. var allValues = values var continue = true while (continue) { val previousSize = allValues.size allValues ++= allValues.flatMap(requirements) continue = allValues.size != previousSize } // Create graph edges and nodes. val edges = allValues.flatMap(v => requirements(v).map(r => (v, r))) val nodes = allValues.map(value => { value -> Node(value, edges.filter(e => e._2 == value).map(_._1)) }).toMap // Create initial set of unmarked nodes, which consists of all nodes in the graph. var unmarkedNodes = nodes.values.toSet var sortedValues = Seq.empty[T] var hasCycle = false def visit(node: Node[T]): Unit = { if (!node.isPermanentlyMarked && !node.isTemporarilyMarked) { node.isTemporarilyMarked = true node.dependants.foreach(d => visit(nodes(d))) node.isTemporarilyMarked = false node.isPermanentlyMarked = true unmarkedNodes -= node sortedValues = node.value +: sortedValues } else if (node.isTemporarilyMarked) { hasCycle = true } } // Perform depth-first search. while (!hasCycle && unmarkedNodes.nonEmpty) { visit(unmarkedNodes.head) } if (hasCycle) None else Some(sortedValues) } private[TopologicalSort] case class Node[T](value: T, dependants: Set[T]) { private[TopologicalSort] var isTemporarilyMarked: Boolean = false private[TopologicalSort] var isPermanentlyMarked: Boolean = false } }
2,431
32.315068
86
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/utilities/Histogram.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.utilities import scala.collection.Searching._ import scala.collection.mutable /** Efficient streaming histogram implementation based on an algorithm described in * [A Streaming Parallel Decision Tree Algorithm](http://www.jmlr.org/papers/volume11/ben-haim10a/ben-haim10a.pdf). * The histogram consumes numeric samples and maintains a running approximation of the samples distribution using the * specified maximum number of bins. * * This implementation is based on this * [Java/Clojure implementation by Adam Ashenfelter](https://github.com/bigmlcom/histogram). * * @param maxNumBins Maximum number of bins used. * * @author Emmanouil Antonios Platanios */ class Histogram(val maxNumBins: Int) { import Histogram._ protected val binReservoir: BinReservoir = { if (maxNumBins > Histogram.RESERVOIR_THRESHOLD) new TreeBinReservoir(maxNumBins) else new ArrayBinReservoir(maxNumBins) } protected var _minimum: Option[Double] = None protected var _maximum: Option[Double] = None protected var pointToSum: Option[mutable.TreeMap[Double, Double]] = None protected var sumToBin : Option[mutable.TreeMap[Double, Bin]] = None /** Boolean indicating whether the gaps between bins are weighted by the number of samples in the bins. */ @inline def useCountWeightedGaps: Boolean = { binReservoir.useNumSamplesWeightedGaps } /** Number of samples seen after which the bins are fixed. This makes insertions faster after that number of samples * have been seen. */ @inline def freezeThreshold: Option[Long] = { binReservoir.freezeThreshold } /** Number of samples that have been added to this histogram so far. */ @inline def numSamples: Long = { binReservoir.numSamples } /** Minimum value that has been inserted into this histogram. */ @inline def minimum: Option[Double] = { _minimum } /** Maximum value that has been inserted into this histogram. */ @inline def maximum: Option[Double] = { _maximum } /** Collections of bins that form this histogram. */ @inline def bins: Seq[Bin] = { binReservoir.bins } /** Approximate count of the number of times `value` has been observed. */ def count(value: Double): Double = { if (value < _minimum.get || value > _maximum.get) { 0.0 } else if (value == _minimum.get && value == _maximum.get) { Double.PositiveInfinity } else { binReservoir.get(value) match { case Some(_) => val lower = Math.nextAfter(value, Double.NegativeInfinity) val higher = Math.nextAfter(value, Double.PositiveInfinity) val lowerDensity = pdf(lower) val higherDensity = pdf(higher) (lowerDensity + higherDensity) / 2.0 case None => val floorBin = binReservoir.floor(value).getOrElse(Bin(_minimum.get, numSamples = 0L)) val ceilBin = binReservoir.ceil(value).getOrElse(Bin(_maximum.get, numSamples = 0L)) // We compute the density starting from the sum: // s = p + (1/2 + r - r^2/2)*i + r^2/2*i1 // r = (value - m) / (m1 - m) // s_dx = i - (i1 - i) * r val m = floorBin.mean val m1 = ceilBin.mean val r = (value - m) / (m1 - m) val i = floorBin._numSamples.toDouble val i1 = ceilBin._numSamples.toDouble (i + (i1 - i) * r) / (m1 - m) } } } /** Approximate number of observations with value less than `value`. */ def sum(value: Double): Double = { if (binReservoir.numSamples == 0) { 0.0 } else { if (value < _minimum.get) { 0.0 } else if (value > _maximum.get) { binReservoir.numSamples.toDouble } else if (binReservoir.last.exists(_.mean == value)) { binReservoir.numSamples - (binReservoir.last.get._numSamples.toDouble / 2.0) } else { binReservoir.get(value) match { case Some(bin) => getPointToSum(bin.mean) case None => val (binI, previousNumSamples) = binReservoir.floor(value) match { case Some(bin) => (bin, getPointToSum(bin.mean)) case None => ( Bin(mean = _minimum.get, numSamples = 0L), binReservoir.head.map(_._numSamples.toDouble).getOrElse(0.0) / 2.0) } val binI1 = binReservoir.ceil(value) match { case Some(bin) => bin case None => Bin(mean = _maximum.get, numSamples = 0L) } // We derive the sum in terms of p, r, i, and i1, starting from the Ben-Haim paper: // m = i + (i1 - i) * r // s = p + i/2 + (m + i) * r/2 // p' = p + i/2 (the previous value includes i/2) // s = p' + (i + (i1 - i) * r + i) * r/2 // s = p' + (i + r*i1 - r*i + i) * r/2 // s = p' + r/2*i + r^2/2*i1 - r^2/2*i + r/2*i // s = p' + r/2*i + r/2*i - r^2/2*i + r^2/2*i1 // s = p' + r*i - r^2/2*i + r^2/2*i1 // s = p' + (r - r^2/2)*i + r^2/2*i1 val p = previousNumSamples val r = (value - binI.mean) / (binI1.mean - binI.mean) val i = binI._numSamples.toDouble val i1 = binI1._numSamples.toDouble val rSquaredHalf = 0.5 * r * r p + i * (r - rSquaredHalf) + i1 * rSquaredHalf } } } } /** Approximate probability density function. */ def pdf(value: Double): Double = { count(value) / binReservoir.numSamples.toDouble } /** Approximate cumulative density function. */ def cdf(value: Double): Double = { sum(value) / binReservoir.numSamples.toDouble } /** Inserts the provided value into this histogram. * * @param value Value to insert. * @return This histogram, after the insertion has been processed. */ def insert(value: Double): Unit = { insertBin(Bin(mean = value, numSamples = 1)) } /** Inserts the provided bin into this histogram. * * @param bin Bin to insert. * @return This histogram, after the insertion has been processed. */ def insertBin(bin: Bin): Histogram = { if (_minimum.isEmpty || _minimum.get > bin.mean) _minimum = Some(bin.mean) if (_maximum.isEmpty || _maximum.get < bin.mean) _maximum = Some(bin.mean) clearCacheMaps() binReservoir.add(bin) binReservoir.merge() this } protected def getPointToSum: mutable.TreeMap[Double, Double] = { if (pointToSum.isEmpty) refreshCacheMaps() pointToSum.get } protected def getSumToBin: mutable.TreeMap[Double, Bin] = { if (sumToBin.isEmpty) refreshCacheMaps() sumToBin.get } protected def clearCacheMaps(): Unit = { pointToSum = None sumToBin = None } protected def refreshCacheMaps(): Unit = { pointToSum = Some(mutable.TreeMap.empty[Double, Double]) sumToBin = Some(mutable.TreeMap.empty[Double, Bin]) val minBin = Bin(mean = _minimum.get, numSamples = 0L) val maxBin = Bin(mean = _maximum.get, numSamples = 0L) pointToSum.get.put(_minimum.get, 0.0) sumToBin.get.put(0.0, minBin) sumToBin.get.put(numSamples.toDouble, maxBin) var sum = 0.0 var lastBin = minBin binReservoir.bins.foreach(bin => { sum += (bin._numSamples + lastBin._numSamples).toDouble / 2.0 pointToSum.get.put(bin.mean, sum) sumToBin.get.put(sum, bin) lastBin = bin }) sum += lastBin._numSamples.toDouble / 2.0 pointToSum.get.put(_maximum.get, sum) } } object Histogram { private[Histogram] val RESERVOIR_THRESHOLD: Long = 256L def apply(maxNumBins: Int): Histogram = { new Histogram(maxNumBins) } /** Represents a histogram bin. * * @param mean Mean value of samples placed in this histogram bin. */ case class Bin(mean: Double) extends Ordered[Bin] { /** Number of samples placed in this histogram bin. */ private[Histogram] var _numSamples: Long = 0L def numSamples: Long = { _numSamples } def weight: Double = { mean * _numSamples } def combine(other: Bin): Bin = { val numSamples = _numSamples + other._numSamples val combinedBin = Bin(mean = (weight + other.weight) / numSamples.toDouble) combinedBin._numSamples = numSamples combinedBin } override def compare(that: Bin): Int = { Ordering.Double.compare(mean, that.mean) } } object Bin { def apply(mean: Double, numSamples: Long): Bin = { val bin = Bin(mean) bin._numSamples = numSamples bin } } /** Data structure for managing histogram bins (i.e., insertion of bins, merging of bins, etc.). */ trait BinReservoir { val maxNumBins : Int val useNumSamplesWeightedGaps: Boolean val freezeThreshold : Option[Long] protected var _numSamples: Long = 0L @inline def isFrozen: Boolean = { freezeThreshold.exists(_ < _numSamples) } @inline def numSamples: Long = { _numSamples } def add(bin: Bin): Unit def head: Option[Bin] def last: Option[Bin] def get(value: Double): Option[Bin] def floor(value: Double): Option[Bin] def ceil(value: Double): Option[Bin] def bins: Seq[Bin] def merge(): Unit def gapWeight(previous: Bin, next: Bin): Double = { if (!useNumSamplesWeightedGaps) next.mean - previous.mean else (next.mean - previous.mean) * math.log(math.E + math.min(previous._numSamples, next._numSamples).toDouble) } } /** This bin reservoir implements bin operations (insertions, merges, etc.), using an underlying array buffer. It is * best used for histograms with a small (i.e., `<= 256`) number of bins. It has O(N) insertion performance with * respect to the number of bins in the histogram. For histograms with more bins, the `TreeBinReservoir` class offers * better performance. * * @param maxNumBins Maximum number of bins. * @param useNumSamplesWeightedGaps Boolean value indicating whether to weigh the gaps between bins by the number of * samples in those bins. * @param freezeThreshold Optional threshold specifying the number of samples seen after which the bins * are fixed. This makes insertions faster after that number of samples have been * seen. */ class ArrayBinReservoir( override val maxNumBins: Int, override val useNumSamplesWeightedGaps: Boolean = false, override val freezeThreshold: Option[Long] = None ) extends BinReservoir { protected val _bins: mutable.ArrayBuffer[Bin] = mutable.ArrayBuffer.empty[Bin] override def add(bin: Bin): Unit = { _numSamples += bin._numSamples _bins.search(bin) match { case Found(index) => _bins(index)._numSamples += bin._numSamples case InsertionPoint(index) if !isFrozen || _bins.size != maxNumBins => _bins.insert(index, bin) case InsertionPoint(index) => val previousIndex = index - 1 val previousDistance = if (previousIndex >= 0) bin.mean - _bins(previousIndex).mean else Double.MaxValue val nextDistance = if (index < _bins.size) _bins(index).mean - bin.mean else Double.MaxValue if (previousDistance < nextDistance) _bins(previousIndex)._numSamples += bin._numSamples else _bins(index)._numSamples += bin._numSamples } } override def head: Option[Bin] = { _bins.headOption } override def last: Option[Bin] = { _bins.lastOption } override def get(p: Double): Option[Bin] = { _bins.search(Bin(p)) match { case Found(index) => Some(_bins(index)) case _ => None } } override def floor(p: Double): Option[Bin] = { _bins.search(Bin(p)) match { case Found(index) => Some(_bins(index)) case InsertionPoint(index) if index > 0 => Some(_bins(index - 1)) case _ => None } } override def ceil(p: Double): Option[Bin] = { _bins.search(Bin(p)) match { case Found(index) => Some(_bins(index)) case InsertionPoint(index) if index < _bins.size => Some(_bins(index)) case _ => None } } override def bins: Seq[Bin] = { _bins } override def merge(): Unit = { while (_bins.size > maxNumBins) { var minGap = Double.MaxValue var minGapIndex = -1 for (i <- 0 until (_bins.size - 1)) { val gap = gapWeight(_bins(i), _bins(i + 1)) if (minGap > gap) { minGap = gap minGapIndex = i } } val previousBin = _bins(minGapIndex) val nextBin = _bins.remove(minGapIndex + 1) _bins.update(minGapIndex, previousBin.combine(nextBin)) } } } /** This bin reservoir implements bin operations (insertions, merges, etc.), using an underlying tree map. It is * best used for histograms with a large (i.e., `> 256`) number of bins. It has O(log(N)) insertion performance with * respect to the number of bins in the histogram. For histograms with fewer bins, the `ArrayBinReservoir` class * offers better performance. * * @param maxNumBins Maximum number of bins. * @param useNumSamplesWeightedGaps Boolean value indicating whether to weigh the gaps between bins by the number of * samples in those bins. * @param freezeThreshold Optional threshold specifying the number of samples seen after which the bins * are fixed. This makes insertions faster after that number of samples have been * seen. */ class TreeBinReservoir( override val maxNumBins: Int, override val useNumSamplesWeightedGaps: Boolean = false, override val freezeThreshold: Option[Long] = None ) extends BinReservoir { import TreeBinReservoir.Gap protected val _bins : mutable.TreeMap[Double, Bin] = mutable.TreeMap.empty[Double, Bin] protected val _gaps : mutable.TreeSet[Gap] = mutable.TreeSet.empty[Gap] protected val _valuesToGaps: mutable.HashMap[Double, Gap] = mutable.HashMap.empty[Double, Gap] override def add(bin: Bin): Unit = { _numSamples += bin._numSamples if (isFrozen && _bins.size == maxNumBins) { var floorDifference = Double.MaxValue val floorBin = this.floor(bin.mean) floorBin.foreach(b => floorDifference = math.abs(b.mean - bin.mean)) var ceilDifference = Double.MaxValue val ceilBin = this.ceil(bin.mean) ceilBin.foreach(b => ceilDifference = math.abs(b.mean - bin.mean)) if (floorDifference <= ceilDifference) floorBin.get._numSamples += bin.numSamples else ceilBin.get._numSamples += bin.numSamples } else { get(bin.mean) match { case Some(existingBin) => existingBin._numSamples += bin.numSamples if (useNumSamplesWeightedGaps) updateGaps(existingBin) case None => updateGaps(bin) _bins.put(bin.mean, bin) } } } override def head: Option[Bin] = { _bins.headOption.map(_._2) } override def last: Option[Bin] = { _bins.lastOption.map(_._2) } override def get(value: Double): Option[Bin] = { _bins.get(value) } override def floor(value: Double): Option[Bin] = { _bins.to(value).lastOption.map(_._2) } override def ceil(value: Double): Option[Bin] = { _bins.from(value).headOption.map(_._2) } override def bins: Seq[Bin] = { _bins.values.toSeq } override def merge(): Unit = { while (_bins.size > maxNumBins) { val minGap = _gaps.head _gaps.remove(minGap) _valuesToGaps.get(minGap.endBin.mean) match { case Some(followingGap) => _gaps.remove(followingGap) case None => () } _bins.remove(minGap.startBin.mean) _bins.remove(minGap.endBin.mean) _valuesToGaps.remove(minGap.startBin.mean) _valuesToGaps.remove(minGap.endBin.mean) val newBin = minGap.startBin.combine(minGap.endBin) updateGaps(newBin) _bins.put(newBin.mean, newBin) } } protected def updateGaps(newBin: Bin): Unit = { floor(newBin.mean).foreach(updateGaps(_, newBin)) ceil(newBin.mean).foreach(updateGaps(newBin, _)) } protected def updateGaps(previousBin: Bin, nextBin: Bin): Unit = { val newGap = Gap(previousBin, nextBin, gapWeight(previousBin, nextBin)) _valuesToGaps.get(previousBin.mean) match { case Some(previousGap) => _gaps.remove(previousGap) case None => () } _valuesToGaps.put(previousBin.mean, newGap) _gaps.add(newGap) } } object TreeBinReservoir { case class Gap(startBin: Bin, endBin: Bin, space: Double) extends Ordered[Gap] { override def compare(that: Gap): Int = { var result = Ordering.Double.compare(space, that.space) if (result == 0) result = startBin.compare(that.startBin) result } } } }
18,088
33.194707
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/utilities/PriorityCounter.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.utilities import scala.collection.mutable /** Counter backed by a priority queue. * * This class allows counting elements, while providing constant time access to the element with the highest count at * any point in time. It is useful for algorithms similar to the one used to learn byte-pair-encodings of words, given * large text corpora. * * @author Emmanouil Antonios Platanios */ class PriorityCounter[A] extends scala.Cloneable { /** Internal array used by this priority counter to store all elements being counted. */ protected val internalArray = new PriorityCounter.ResizableArrayAccess[(Long, A)] /** Map from element to location index in the internal array. */ protected val locations = mutable.Map.empty[A, Int] /** Swaps the element stored at `index1` in the internal array, with that stored at `index2`. */ protected def swap(index1: Int, index2: Int): Unit = { val element1 = cast(internalArray.p_array(index1))._2 val element2 = cast(internalArray.p_array(index2))._2 internalArray.p_swap(index1, index2) locations.update(element1, index2) locations.update(element2, index1) } // We do not use the first element of the array. internalArray.p_size0 += 1 /** Returns the size of this counter (i.e., the number of elements it contains). */ def size: Int = internalArray.length - 1 /** Returns `true` if this counter does not contain any elements. */ def isEmpty: Boolean = internalArray.p_size0 < 2 /** Returns `true` if this counter is not empty. */ def nonEmpty: Boolean = !isEmpty /** Casts an element of the internal array to the element type managed by this priority counter. */ protected def cast(x: AnyRef): (Long, A) = x.asInstanceOf[(Long, A)] /** Fixes the order of the elements in `as`, upwards from position `m` (i.e., `m` to `0`). * * @return Boolean value indicating whether any swaps were made. */ protected def fixUp(m: Int): Boolean = { var k: Int = m while (k > 1 && cast(internalArray.p_array(k / 2))._1 < cast(internalArray.p_array(k))._1) { swap(k, k / 2) k = k / 2 } k != m } /** Fixes the order of the elements in `as`, downwards from position `m` until position `n`. * * @return Boolean value indicating whether any swaps were made. */ protected def fixDown(m: Int, n: Int): Boolean = { var k: Int = m while (n >= 2 * k) { var j = 2 * k if (j < n && cast(internalArray.p_array(j))._1 < cast(internalArray.p_array(j + 1))._1) j += 1 if (cast(internalArray.p_array(k))._1 >= cast(internalArray.p_array(j))._1) { return k != m } else { swap(k, j) k = j } } k != m } /** Updates the count for the provided element. * * @param element Element whose count to update. * @param count Count value to use. * @return This priority counter. */ def update(element: A, count: Long): this.type = { internalUpdate(element, count, _ => count) } /** Adds the provided value to the count of the provided element. * * @param element Element whose count to update. * @param count Count value to add. * @return This priority counter. */ def add(element: A, count: Long): this.type = { internalUpdate(element, count, location => cast(internalArray.p_array(location))._1 + count) } /** Updates the count for the provided element. * * @param element Element whose count to update. * @param count Count value to use, if `element` is a new element. * @param updateFn Function that takes the location of the element being updated and returns the count value to use. * @return This priority counter. */ protected def internalUpdate(element: A, count: Long, updateFn: (Int) => Long): this.type = { val location = locations.getOrElseUpdate(element, internalArray.p_size0) if (location == internalArray.p_size0) { internalArray.p_ensureSize(internalArray.p_size0 + 1) internalArray.p_array(internalArray.p_size0) = (count, element).asInstanceOf[AnyRef] fixUp(internalArray.p_size0) internalArray.p_size0 += 1 } else { internalArray.p_array(location) = (updateFn(location), element).asInstanceOf[AnyRef] fixUp(location) fixDown(location, internalArray.p_size0 - 1) } this } /** Returns the element with the highest count and removes it from this counter. * * @return Element with the highest count, along with that count. * @throws java.util.NoSuchElementException If there are no elements in this counter. */ @throws[NoSuchElementException] def dequeueMax(): (Long, A) = { if (internalArray.p_size0 > 1) { internalArray.p_size0 -= 1 val result = cast(internalArray.p_array(1)) locations -= result._2 val last = internalArray.p_array(internalArray.p_size0) internalArray.p_array(1) = last internalArray.p_array(internalArray.p_size0) = null val castedLast = cast(last) locations.update(castedLast._2, 1) fixDown(1, internalArray.p_size0 - 1) result } else throw new NoSuchElementException("The priority counter is empty.") } /** Returns the element with the highest count, without removing it from this counter. * * @return Element with the highest count, along with that count. * @throws java.util.NoSuchElementException If there are no elements in this counter. */ def max: (Long, A) = { if (internalArray.p_size0 > 1) cast(internalArray.p_array(1)) else throw new NoSuchElementException("The priority counter is empty.") } /** Removes all elements from this counter. After this operation is completed, the counter will be empty. */ def clear(): Unit = { internalArray.p_size0 = 1 } /** Clones this counter. * * @return A priority counter with the same elements as this one. */ override def clone(): PriorityCounter[A] = { val pq = new PriorityCounter[A] val n = internalArray.p_size0 pq.internalArray.p_ensureSize(n) java.lang.System.arraycopy(internalArray.p_array, 1, pq.internalArray.p_array, 1, n - 1) pq.internalArray.p_size0 = n pq.locations ++= locations.toSeq pq } } object PriorityCounter { def apply[A](): PriorityCounter[A] = new PriorityCounter[A]() /** Wrapper around the resizable array class that provides access to some of its protected fields. */ protected[PriorityCounter] class ResizableArrayAccess[T] extends mutable.AbstractSeq[T] with mutable.ResizableArray[T] with Serializable { def p_size0: Int = size0 def p_size0_=(s: Int): Unit = size0 = s def p_array: Array[AnyRef] = array def p_ensureSize(n: Int): Unit = super.ensureSize(n) def p_swap(a: Int, b: Int): Unit = super.swap(a, b) } }
7,536
36.128079
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/utilities/BoundedPriorityQueue.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.utilities import java.io.Serializable import java.util.{PriorityQueue => JPriorityQueue} import scala.collection.JavaConverters._ import scala.collection.generic.Growable /** Bounded priority queue. * * This class wraps the original Java `PriorityQueue` class and modifies it such that only the top `maxSize` elements * are retained. The top `maxSize` elements are defined by an implicit `Ordering[A]`. * * @param maxSize Number of elements to retain. If less than `1`, all elements are retained. * @param ord Implicit ordering to use for the elements. * * @author Emmanouil Antonios Platanios */ private[utilities] class BoundedPriorityQueue[A](maxSize: Int)(implicit ord: Ordering[A]) extends Iterable[A] with Growable[A] with Serializable { private val underlying = { if (maxSize < 1) { new JPriorityQueue[A](ord) } else { new JPriorityQueue[A](maxSize, ord) } } override def iterator: Iterator[A] = { underlying.iterator.asScala } override def size: Int = { underlying.size } override def ++=(xs: TraversableOnce[A]): this.type = { xs.foreach(this += _) this } override def +=(elem: A): this.type = { if (maxSize < 1 || size < maxSize) underlying.offer(elem) else maybeReplaceLowest(elem) this } def poll(): A = { underlying.poll() } override def +=(elem1: A, elem2: A, elems: A*): this.type = { this += elem1 += elem2 ++= elems } override def clear(): Unit = { underlying.clear() } private def maybeReplaceLowest(a: A): Boolean = { val head = underlying.peek() if (head != null && ord.gt(a, head)) { underlying.poll() underlying.offer(a) } else { false } } } object BoundedPriorityQueue { def apply[A](maxSize: Int)(implicit ord: Ordering[A]): BoundedPriorityQueue[A] = { new BoundedPriorityQueue[A](maxSize)(ord) } }
2,588
26.542553
118
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/utilities/MutableFile.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.utilities import better.files.File /** Helper class used to represent mutable files. This class is useful for the data preprocessing steps. * * @param file File being wrapped. * * @author Emmanouil Antonios Platanios */ private[mt] class MutableFile protected (protected var file: File) { def set(file: File): Unit = { this.file = file } def get: File = { file } } private[mt] object MutableFile { def apply(file: File): MutableFile = { new MutableFile(file) } }
1,172
27.609756
104
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/utilities/CompressedFiles.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.utilities import better.files._ import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import org.apache.commons.compress.utils.IOUtils import java.io.InputStream import java.util.zip.GZIPInputStream /** * @author Emmanouil Antonios Platanios */ object CompressedFiles { def decompressTGZ(tgzFile: File, destination: File, bufferSize: Int = 8192): Unit = { decompressTGZStream(tgzFile.newInputStream, destination, bufferSize) } def decompressTar(tarFile: File, destination: File, bufferSize: Int = 8192): Unit = { decompressTarStream(tarFile.newInputStream, destination, bufferSize) } def decompressTGZStream(tgzStream: InputStream, destination: File, bufferSize: Int = 8192): Unit = { decompressTarStream(new GZIPInputStream(tgzStream), destination, bufferSize) } def decompressTarStream(tarStream: InputStream, destination: File, bufferSize: Int = 8192): Unit = { val inputStream = new TarArchiveInputStream(tarStream) var entry = inputStream.getNextTarEntry while (entry != null) { if (!entry.isDirectory) IOUtils.copy(inputStream, destination.createChild(entry.getName, createParents = true).newFileOutputStream()) entry = inputStream.getNextTarEntry } inputStream.close() } }
1,945
36.423077
117
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/utilities/TrieWordCounter.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.utilities import java.util.concurrent.atomic.AtomicLong import scala.collection.mutable /** Word counter data structure that uses a TRIE as the underlying data structure. * * @author Emmanouil Antonios Platanios */ case class TrieWordCounter() { protected val rootNode: TrieWordCounter.TrieNode = TrieWordCounter.TrieNode() protected var _totalCount: Long = { 0L } def insertWord(word: String): Long = { _totalCount += 1 var currentNode = rootNode for (char <- word) currentNode = currentNode.child(char) currentNode.incrementCount() } def insertWordWithCount(word: String, count: Long): Unit = { _totalCount += count var currentNode = rootNode for (char <- word) currentNode = currentNode.child(char) currentNode.setCount(count) } def apply(word: String): Long = { var currentNode = rootNode for (char <- word) currentNode = currentNode.child(char) currentNode.count } def totalCount: Long = { _totalCount } def words(sizeThreshold: Int = -1, countThreshold: Int = -1): Iterable[(Long, String)] = { if (sizeThreshold == -1 && countThreshold == -1) { rootNode.words.filter(_._2 != "") } else if (sizeThreshold == -1) { rootNode.words.filter(w => w._2 != "" && w._1 >= countThreshold) } else { val words = BoundedPriorityQueue[(Long, String)](sizeThreshold) rootNode.words.filter(_._2 != "").foreach { case (count, word) if countThreshold < 0 || count >= countThreshold => words += ((count, word)) case _ => () } words } } } object TrieWordCounter { case class TrieNode() { protected val _count : AtomicLong = new AtomicLong(0L) protected val _children: mutable.LongMap[TrieNode] = mutable.LongMap.empty[TrieNode] def count: Long = _count.get() def incrementCount(): Long = _count.incrementAndGet() def setCount(count: Long): Unit = _count.set(count) def child(char: Long): TrieNode = _children.getOrElseUpdate(char, TrieNode()) def children: Seq[(Long, TrieNode)] = _children.toSeq def words: Iterable[(Long, String)] = { val words = (count, "") +: children.flatMap { case (char, childNode) => childNode.words.map { case (count, word) => (count, char.toChar + word) } } words.filter(_._1 > 0) } } }
3,067
29.989899
103
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/utilities/Encoding.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.utilities import java.nio.charset.StandardCharsets /** * @author Emmanouil Antonios Platanios */ object Encoding { def tfStringToUTF8(value: String): String = { new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8) } }
929
32.214286
83
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/ParallelDatasetLoader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.processors.FileProcessor import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.symphony.mt.utilities.{CompressedFiles, MutableFile} import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import java.io.IOException import java.net.URL import java.nio.file.Path import scala.collection.mutable // TODO: [DATA] Place processed files in a different directory. /** Parallel dataset used for machine translation experiments. * * @author Emmanouil Antonios Platanios */ abstract class ParallelDatasetLoader(val srcLanguage: Language, val tgtLanguage: Language) { def name: String def dataConfig: DataConfig def downloadsDir: Path = dataConfig.dataDir protected def src: String = srcLanguage.abbreviation protected def tgt: String = tgtLanguage.abbreviation /** Sequence of files to download as part of this dataset. */ def filesToDownload: Seq[(String, String)] /** Downloaded files listed in `filesToDownload`. */ protected val downloadedFiles: Seq[File] = { filesToDownload.map { case (url, filename) => val path = File(downloadsDir) / filename ParallelDatasetLoader.maybeDownload(path, url, dataConfig.loaderBufferSize) path } } /** Extracted files (if needed) from `downloadedFiles`. */ protected val extractedFiles: Seq[File] = { downloadedFiles.flatMap( ParallelDatasetLoader.maybeExtractTGZ(_, dataConfig.loaderBufferSize) .listRecursively .filter(_.isRegularFile)) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { Seq.empty } /** Returns the source and the target language vocabularies of this dataset. */ def vocabularies: (Seq[File], Seq[File]) = { (Seq.empty, Seq.empty) } /** Returns the files included in this dataset, grouped based on their role. */ def load(): FileParallelDataset = { ParallelDatasetLoader.load(Seq(this))._1.head } } object ParallelDatasetLoader { private[data] val logger = Logger(LoggerFactory.getLogger("Data / Parallel Dataset Loader")) def maybeDownload(file: File, url: String, bufferSize: Int = 8192): Boolean = { if (file.exists) { false } else { try { logger.info(s"Downloading file '$url'.") file.parent.createDirectories() val connection = new URL(url).openConnection() val contentLength = connection.getContentLengthLong val inputStream = connection.getInputStream val outputStream = file.newOutputStream val buffer = new Array[Byte](bufferSize) var progress = 0L var progressLogTime = System.currentTimeMillis Stream.continually(inputStream.read(buffer)).takeWhile(_ != -1).foreach(numBytes => { outputStream.write(buffer, 0, numBytes) progress += numBytes val time = System.currentTimeMillis if (time - progressLogTime >= 1e4) { val numBars = Math.floorDiv(10 * progress, contentLength).toInt logger.info( s"│${"═" * numBars}${" " * (10 - numBars)}│ " + s"%${contentLength.toString.length}s / $contentLength bytes downloaded.".format(progress)) progressLogTime = time } }) outputStream.close() logger.info( s"│${"═" * 10}│ %${contentLength.toString.length}s / $contentLength bytes downloaded.".format(progress)) logger.info(s"Downloaded file '$url'.") true } catch { case e: IOException => logger.error(s"Could not download file '$url'", e) throw e } } } def maybeExtractTGZ(file: File, bufferSize: Int = 8192): File = { if (file.extension(includeAll = true).exists(ext => ext == ".tgz" || ext == ".tar.gz")) { val processedFile = file.sibling(file.nameWithoutExtension(includeAll = true)) if (processedFile.notExists) { ParallelDatasetLoader.logger.info(s"Extracting $file.") CompressedFiles.decompressTGZ(file, processedFile, bufferSize) ParallelDatasetLoader.logger.info(s"Extracted $file.") } processedFile } else { file } } def load( loaders: Seq[ParallelDatasetLoader], workingDir: Option[File] = None ): (Seq[FileParallelDataset], Seq[(Language, Vocabulary)]) = { ParallelDatasetLoader.logger.info("Preprocessing any downloaded files.") // Collect all files. val files = loaders.map(loader => { var srcFiles = Seq.empty[MutableFile] var tgtFiles = Seq.empty[MutableFile] var fileTypes = Seq.empty[DatasetType] var fileTags = Seq.empty[ParallelDataset.Tag] DatasetType.types.foreach(datasetType => { val corpora = loader.corpora(datasetType) // Apply the file processors. val processedCorpora = corpora.map(c => { val processed = c._4(c._2, c._3, loader.srcLanguage, loader.tgtLanguage) (c._1, processed._1, processed._2) }) // Tokenize the corpora. val tokenizedSrcFiles = processedCorpora.map(_._2).map(f => { loader.dataConfig.tokenizer.tokenizeCorpus( f, loader.srcLanguage, loader.dataConfig.loaderBufferSize) }) val tokenizedTgtFiles = processedCorpora.map(_._3).map(f => { loader.dataConfig.tokenizer.tokenizeCorpus( f, loader.tgtLanguage, loader.dataConfig.loaderBufferSize) }) // TODO: [DATA] Only clean the training data. // Clean the corpora. val cleaner = loader.dataConfig.cleaner val (cleanedSrcFiles, cleanedTgtFiles) = tokenizedSrcFiles.zip(tokenizedTgtFiles).map { case (srcFile, tgtFile) => cleaner.cleanCorporaPair(srcFile, tgtFile, loader.dataConfig.loaderBufferSize) }.unzip // Tokenize source and target files. srcFiles ++= cleanedSrcFiles.map(MutableFile(_)) tgtFiles ++= cleanedTgtFiles.map(MutableFile(_)) fileTypes ++= Seq.fill(corpora.length)(datasetType) fileTags ++= corpora.map(_._1) }) (srcFiles, tgtFiles, fileTypes, fileTags) }) ParallelDatasetLoader.logger.info("Preprocessed any downloaded files.") // Generate vocabularies, if necessary. val vocabularies = mutable.Map.empty[Language, mutable.ListBuffer[File]] loaders.foreach(loader => { vocabularies.getOrElseUpdate(loader.srcLanguage, mutable.ListBuffer.empty).append(loader.vocabularies._1: _*) vocabularies.getOrElseUpdate(loader.tgtLanguage, mutable.ListBuffer.empty).append(loader.vocabularies._2: _*) }) val vocabDir = workingDir.getOrElse(File(loaders.head.dataConfig.dataDir)) / "vocabularies" // Collect all tokenized files per language. val tokenizedFiles = vocabularies.keys.toSeq.map(language => language -> { loaders.zip(files).flatMap { case (loader, f) if loader.srcLanguage == language => f._1 case (loader, f) if loader.tgtLanguage == language => f._2 case _ => Seq.empty } }) // Obtain/Generate the vocabulary for each language. val vocabulary = loaders.head.dataConfig.vocabulary match { case NoVocabulary => vocabularies.keys.map(_ -> null).toMap // TODO: Avoid using nulls. case GeneratedVocabulary(generator, shared) => val languages = tokenizedFiles.map(_._1) generator.generate(languages, tokenizedFiles.map(_._2), vocabDir, shared = shared) languages.zip(generator.getVocabularies(languages, vocabDir, shared = shared)).toMap case MergedVocabularies => vocabularies.toMap.map { case (l, v) => if (v.lengthCompare(1) == 0) { l -> Vocabulary(v.head) } else if (v.nonEmpty) { val vocabFilename = loaders.head.dataConfig.vocabulary.filename(Seq(l)) val vocabFile = vocabDir.createChild(vocabFilename, createParents = true) val writer = newWriter(vocabFile) v.toStream .flatMap(_.lineIterator).toSet .filter(_ != "") .foreach(word => writer.write(word + "\n")) writer.flush() writer.close() l -> Vocabulary(vocabFile) } else { throw new IllegalArgumentException("No existing vocabularies found to merge.") } } } val datasets = loaders.zip(files).map { case (loader, (srcFiles, tgtFiles, fileTypes, fileTags)) => val groupedFiles = Map(loader.srcLanguage -> srcFiles.map(_.get), loader.tgtLanguage -> tgtFiles.map(_.get)) val filteredVocabulary = vocabulary.filterKeys(l => l == loader.srcLanguage || l == loader.tgtLanguage) FileParallelDataset(loader.name, filteredVocabulary, loader.dataConfig, groupedFiles, fileTypes, fileTags) } (datasets, vocabulary.toSeq) } }
9,766
38.2249
116
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/package.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt import better.files._ import java.io.{BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter} import java.nio.charset._ import java.nio.file.StandardOpenOption package object data { private[mt] def newReader(file: File): BufferedReader = { val decoder: CharsetDecoder = StandardCharsets.UTF_8.newDecoder() decoder.onMalformedInput(CodingErrorAction.IGNORE) decoder.onUnmappableCharacter(CodingErrorAction.IGNORE) new BufferedReader( new InputStreamReader( file.newInputStream(), decoder)) } private[mt] def newWriter(file: File): BufferedWriter = { val encoder: CharsetEncoder = StandardCharsets.UTF_8.newEncoder() encoder.onMalformedInput(CodingErrorAction.IGNORE) encoder.onUnmappableCharacter(CodingErrorAction.IGNORE) new BufferedWriter( new OutputStreamWriter( file.newOutputStream(Seq( StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)), encoder)) } }
1,702
34.479167
86
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/TensorParallelDataset.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.vocabulary.Vocabulary import org.platanios.tensorflow.api._ /** * @author Emmanouil Antonios Platanios */ class TensorParallelDataset protected ( override val name: String, override val vocabulary: Map[Language, Vocabulary], val tensors: Map[Language, Seq[(Tensor[String], Tensor[Int])]], val tensorTypes: Seq[DatasetType] = null, val tensorTags: Seq[ParallelDataset.Tag] = null ) extends ParallelDataset { override def isEmpty: Boolean = tensors.head._2.isEmpty override def nonEmpty: Boolean = !isEmpty override def filterLanguages(languages: Language*): TensorParallelDataset = { TensorParallelDataset( s"$name/${languages.map(_.abbreviation).mkString("-")}", vocabulary.filterKeys(languages.contains), tensors.filterKeys(languages.contains), tensorTypes, tensorTags) } override def filterTypes(types: DatasetType*): TensorParallelDataset = { require(tensorTypes.nonEmpty, "Cannot filter a parallel dataset by tensor type when it contains no tensor types.") val filteredGroupedTensors = tensors.mapValues(_.zip(tensorTypes).filter(f => types.contains(f._2)).map(_._1)) val filteredFileTypes = tensorTypes.filter(types.contains) val filteredFileKeys = tensorTags.zip(tensorTypes).filter(f => types.contains(f._2)).map(_._1) TensorParallelDataset( s"$name/${types.mkString("-")}", vocabulary, filteredGroupedTensors, filteredFileTypes, filteredFileKeys) } override def filterTags(tags: ParallelDataset.Tag*): TensorParallelDataset = { require(tensorTags.nonEmpty, "Cannot filter a parallel dataset by tensor key when it contains no tensor keys.") val filteredGroupedTensors = tensors.mapValues(_.zip(tensorTags).filter(f => tags.contains(f._2)).map(_._1)) val filteredTensorTypes = tensorTags.zip(tensorTypes).filter(f => tags.contains(f._1)).map(_._2) val filteredTensorsKeys = tensorTags.filter(tags.contains) TensorParallelDataset( s"$name/${tags.mkString("-")}", vocabulary, filteredGroupedTensors, filteredTensorTypes, filteredTensorsKeys) } } object TensorParallelDataset { def apply( name: String, vocabularies: Map[Language, Vocabulary], tensors: Map[Language, Seq[(Tensor[String], Tensor[Int])]], tensorTypes: Seq[DatasetType] = null, tensorTags: Seq[ParallelDataset.Tag] = null ): TensorParallelDataset = { new TensorParallelDataset(name, vocabularies, tensors, tensorTypes, tensorTags) } }
3,224
42.581081
118
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/DataConfig.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data import org.platanios.symphony.mt.data.processors._ import org.platanios.symphony.mt.vocabulary._ import java.nio.file.{Path, Paths} /** * @author Emmanouil Antonios Platanios */ case class DataConfig( // Loader dataDir: Path = Paths.get("data"), loaderBufferSize: Int = 8192, tokenizer: Tokenizer = MosesTokenizer(), cleaner: Cleaner = MosesCleaner(), vocabulary: DatasetVocabulary = GeneratedVocabulary(SimpleVocabularyGenerator(50000, -1, bufferSize = 8192)), // Corpus trainBatchSize: Long = 128, inferBatchSize: Long = 32, evalBatchSize: Long = 32, numBuckets: Int = 5, bucketAdaptedBatchSize: Boolean = true, srcMaxLength: Int = 50, tgtMaxLength: Int = 50, shuffleBufferSize: Long = -1L, numPrefetchedBatches: Long = 10L, numParallelCalls: Int = 4)
1,504
33.204545
113
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/ParallelDataset.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.vocabulary.Vocabulary /** * @author Emmanouil Antonios Platanios */ trait ParallelDataset { val name : String val vocabulary: Map[Language, Vocabulary] def supportsLanguage(language: Language): Boolean = vocabulary.contains(language) @throws[IllegalArgumentException] protected def checkSupportsLanguage(language: Language): Unit = { if (!supportsLanguage(language)) throw new IllegalArgumentException(s"Dataset '$name' does not support the $language language.") } def languages: Set[Language] = vocabulary.keySet def languagePairs( includeIdentity: Boolean = false, includeReverse: Boolean = true ): Set[(Language, Language)] = { var pairs = languages.toSeq.combinations(2) .map(c => (c(0), c(1))) if (includeIdentity) pairs = pairs.flatMap(p => Seq(p, (p._1, p._1), (p._2, p._2))) if (includeReverse) pairs = pairs.flatMap(p => Seq(p, (p._2, p._1))) pairs.toSet } def isEmpty: Boolean def nonEmpty: Boolean def filterLanguages(languages: Language*): ParallelDataset def filterTypes(fileTypes: DatasetType*): ParallelDataset def filterTags(tags: ParallelDataset.Tag*): ParallelDataset } object ParallelDataset { trait Tag { val value: String override def toString: String = value } }
2,053
30.6
101
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/DatasetType.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data /** * @author Emmanouil Antonios Platanios */ sealed trait DatasetType { override def toString: String } object DatasetType { def types: Set[DatasetType] = Set(Train, Dev, Test) } case object Train extends DatasetType { override def toString: String = "Train" } case object Dev extends DatasetType { override def toString: String = "Dev" } case object Test extends DatasetType { override def toString: String = "Test" }
1,114
26.875
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/DatasetVocabulary.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.vocabulary.VocabularyGenerator /** * @author Emmanouil Antonios Platanios */ sealed trait DatasetVocabulary { /** Returns the vocabulary file name that this vocabulary uses. * * @param languages Languages for which a vocabulary will be generated. * @return Vocabulary file name. */ def filename(languages: Seq[Language]): String = s"vocab.${languages.map(_.abbreviation).sorted.mkString(".")}" override def toString: String } case object NoVocabulary extends DatasetVocabulary { override def toString: String = "v:none" } case object MergedVocabularies extends DatasetVocabulary { override def toString: String = "v:merged" } case class GeneratedVocabulary( generator: VocabularyGenerator, shared: Boolean = false ) extends DatasetVocabulary { /** Returns the vocabulary file name that this vocabulary uses. * * @param languages Languages for which a vocabulary will be generated. * @return Vocabulary file name. */ override def filename(languages: Seq[Language]): String = generator.filename(languages) override def toString: String = { if (shared) s"v:${generator.toString}:shared" else s"v:${generator.toString}" } }
1,961
31.163934
113
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/FileParallelDataset.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.vocabulary.Vocabulary import better.files.File /** * @author Emmanouil Antonios Platanios */ class FileParallelDataset protected ( override val name: String, override val vocabulary: Map[Language, Vocabulary], val dataConfig: DataConfig, val files: Map[Language, Seq[File]], val fileTypes: Seq[DatasetType] = null, val fileTags: Seq[ParallelDataset.Tag] = null ) extends ParallelDataset { override def isEmpty: Boolean = files.head._2.isEmpty override def nonEmpty: Boolean = !isEmpty override def filterLanguages(languages: Language*): FileParallelDataset = { FileParallelDataset( s"$name/${languages.map(_.abbreviation).mkString("-")}", vocabulary.filterKeys(languages.contains), dataConfig, files.filterKeys(languages.contains), fileTypes, fileTags) } override def filterTypes(types: DatasetType*): FileParallelDataset = { val filteredGroupedFiles = files.mapValues(_.zip(fileTypes).filter(f => types.contains(f._2)).map(_._1)) val filteredFileTypes = fileTypes.filter(types.contains) val filteredFileKeys = fileTags.zip(fileTypes).filter(f => types.contains(f._2)).map(_._1) FileParallelDataset( s"$name/${types.mkString("-")}", vocabulary, dataConfig, filteredGroupedFiles, filteredFileTypes, filteredFileKeys) } override def filterTags(tags: ParallelDataset.Tag*): FileParallelDataset = { require(fileTags.nonEmpty, "Cannot filter a parallel dataset by file tag when it contains no file tags.") val filteredGroupedFiles = files.mapValues(_.zip(fileTags).filter(f => tags.contains(f._2)).map(_._1)) val filteredFileTypes = fileTags.zip(fileTypes).filter(f => tags.contains(f._1)).map(_._2) val filteredFileKeys = fileTags.filter(tags.contains) FileParallelDataset( s"$name/${tags.mkString("-")}", vocabulary, dataConfig, filteredGroupedFiles, filteredFileTypes, filteredFileKeys) } override def hashCode(): Int = { val prime = 31 var result = 1 result = prime * result + vocabulary.hashCode result = prime * result + dataConfig.hashCode result = prime * result + files.hashCode result = prime * result + (if (fileTypes == null) 0 else fileTypes.hashCode) result = prime * result + (if (fileTags == null) 0 else fileTags.hashCode) result } override def equals(that: Any): Boolean = { that match { case other: FileParallelDataset => vocabulary == other.vocabulary && dataConfig == other.dataConfig && files == other.files && fileTypes == other.fileTypes && fileTags == other.fileTags case _ => false } } } object FileParallelDataset { def apply( name: String, vocabularies: Map[Language, Vocabulary], dataConfig: DataConfig, files: Map[Language, Seq[File]], fileTypes: Seq[DatasetType] = null, fileTags: Seq[ParallelDataset.Tag] = null ): FileParallelDataset = { new FileParallelDataset(name, vocabularies, dataConfig, files, fileTypes, fileTags) } }
3,801
37.40404
109
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/IWSLT15StanfordLoader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language.{English, Vietnamese} import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors.{FileProcessor, NoFileProcessor} import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class IWSLT15StanfordLoader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage, tgtLanguage) { require( IWSLT15StanfordLoader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the IWSLT-15 dataset.") override def name: String = "IWSLT-15" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("iwslt-15") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("iwslt-15").resolve("downloads") private[this] def reversed: Boolean = { IWSLT15StanfordLoader.supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } private[this] def directoryName: String = if (reversed) s"iwslt15.$tgt-$src" else s"iwslt15.$src-$tgt" /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq( s"${IWSLT15StanfordLoader.url}/$directoryName/${IWSLT15StanfordLoader.trainPrefix}.$src", s"${IWSLT15StanfordLoader.url}/$directoryName/${IWSLT15StanfordLoader.trainPrefix}.$tgt", s"${IWSLT15StanfordLoader.url}/$directoryName/${IWSLT15StanfordLoader.devPrefix}.$src", s"${IWSLT15StanfordLoader.url}/$directoryName/${IWSLT15StanfordLoader.devPrefix}.$tgt", s"${IWSLT15StanfordLoader.url}/$directoryName/${IWSLT15StanfordLoader.testPrefix}.$src", s"${IWSLT15StanfordLoader.url}/$directoryName/${IWSLT15StanfordLoader.testPrefix}.$tgt", s"${IWSLT15StanfordLoader.url}/$directoryName/${IWSLT15StanfordLoader.vocabPrefix}.$src", s"${IWSLT15StanfordLoader.url}/$directoryName/${IWSLT15StanfordLoader.vocabPrefix}.$tgt" ).map(url => (url, url.splitAt(url.lastIndexOf('/') + 1)._2)) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((IWSLT15StanfordLoader.Train, File(downloadsDir) / s"${IWSLT15StanfordLoader.trainPrefix}.$src", File(downloadsDir) / s"${IWSLT15StanfordLoader.trainPrefix}.$tgt", NoFileProcessor)) case Dev => Seq((IWSLT15StanfordLoader.Test2012, File(downloadsDir) / s"${IWSLT15StanfordLoader.devPrefix}.$src", File(downloadsDir) / s"${IWSLT15StanfordLoader.devPrefix}.$tgt", NoFileProcessor)) case Test => Seq((IWSLT15StanfordLoader.Test2013, File(downloadsDir) / s"${IWSLT15StanfordLoader.testPrefix}.$src", File(downloadsDir) / s"${IWSLT15StanfordLoader.testPrefix}.$tgt", NoFileProcessor)) } } /** Returns the source and the target vocabulary of this dataset. */ override def vocabularies: (Seq[File], Seq[File]) = ( Seq(File(downloadsDir) / s"${IWSLT15StanfordLoader.vocabPrefix}.$src"), Seq(File(downloadsDir) / s"${IWSLT15StanfordLoader.vocabPrefix}.$tgt")) } object IWSLT15StanfordLoader { val url : String = "https://nlp.stanford.edu/projects/nmt/data" val trainPrefix: String = "train" val devPrefix : String = "tst2012" val testPrefix : String = "tst2013" val vocabPrefix: String = "vocab" val supportedLanguagePairs: Set[(Language, Language)] = Set((English, Vietnamese)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): IWSLT15StanfordLoader = { new IWSLT15StanfordLoader(srcLanguage, tgtLanguage, dataConfig) } trait Tag extends ParallelDataset.Tag object Tag { @throws[IllegalArgumentException] def fromName(name: String): Tag = name match { case "train" => Train case "tst2012" => Test2012 case "tst2013" => Test2013 case _ => throw new IllegalArgumentException(s"'$name' is not a valid IWSLT-15 Stanford tag.") } } case object Train extends Tag { override val value: String = "train" } case object Test2012 extends Tag { override val value: String = "tst2012" } case object Test2013 extends Tag { override val value: String = "tst2013" } }
5,540
39.152174
108
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/TEDTalksLoader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors.{FileProcessor, TSVConverter} import better.files._ import java.nio.file.Path /** This is a loader for the TED talks dataset in [[https://github.com/neulab/word-embeddings-for-nmt]]. * * @author Emmanouil Antonios Platanios */ class TEDTalksLoader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage, tgtLanguage) { require( TEDTalksLoader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the TED-Talks dataset.") override def name: String = "TED-Talks" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("ted-talks") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("ted-talks").resolve("downloads") /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq((s"${TEDTalksLoader.url}/${TEDTalksLoader.filename}.tar.gz", s"${TEDTalksLoader.filename}.tar.gz")) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((TEDTalksLoader.Train, File(downloadsDir) / TEDTalksLoader.filename / "all_talks_train.tsv", File(downloadsDir) / TEDTalksLoader.filename / "all_talks_train.tsv", TSVConverter)) case Dev => Seq((TEDTalksLoader.Dev, File(downloadsDir) / TEDTalksLoader.filename / "all_talks_dev.tsv", File(downloadsDir) / TEDTalksLoader.filename / "all_talks_dev.tsv", TSVConverter)) case Test => Seq((TEDTalksLoader.Test, File(downloadsDir) / TEDTalksLoader.filename / "all_talks_test.tsv", File(downloadsDir) / TEDTalksLoader.filename / "all_talks_test.tsv", TSVConverter)) } } } object TEDTalksLoader { val url: String = "http://phontron.com/data" val filename: String = "ted_talks" val supportedLanguagePairs: Set[(Language, Language)] = Set( Albanian, Arabic, Armenian, Azerbaijani, Basque, Belarusian, Bengali, Bosnian, Bulgarian, Burmese, Chinese, ChineseMainland, ChineseTaiwan, Croatian, Czech, Danish, Dutch, English, Esperanto, Estonian, Finnish, French, FrenchCanada, Galician, Georgian, German, Greek, Hebrew, Hindi, Hungarian, Indonesian, Italian, Japanese, Kazakh, Korean, Kurdish, Lithuanian, Macedonian, Malay, Marathi, Mongolian, Norwegian, Persian, Polish, Portuguese, PortugueseBrazil, Romanian, Russian, Tamil, Thai, Serbian, Slovak, Slovenian, Swedish, Spanish, Turkish, Ukranian, Urdu, Vietnamese).toSeq.combinations(2).map(p => (p(0), p(1))).toSet def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): TEDTalksLoader = { new TEDTalksLoader(srcLanguage, tgtLanguage, dataConfig) } trait Tag extends ParallelDataset.Tag object Tag { @throws[IllegalArgumentException] def fromName(name: String): Tag = name match { case "train" => Train case "dev" => Dev case "test" => Test case _ => throw new IllegalArgumentException(s"'$name' is not a valid TED-Talks tag.") } } case object Train extends Tag { override val value: String = "train" } case object Dev extends Tag { override val value: String = "dev" } case object Test extends Tag { override val value: String = "test" } }
4,799
37.4
118
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/IWSLT17Loader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors._ import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class IWSLT17Loader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage, tgtLanguage) { require( IWSLT17Loader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the IWSLT-17 dataset.") override def name: String = "IWSLT-17" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("iwslt-17") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("iwslt-17").resolve("downloads") /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq( (s"${IWSLT17Loader.url}/${IWSLT17Loader.filename}.tgz", s"${IWSLT17Loader.filename}.tgz"), (s"${IWSLT17Loader.testUrl}/$src/$tgt/$src-$tgt.tgz", s"$src-$tgt.tgz"), (s"${IWSLT17Loader.testUrl}/$tgt/$src/$tgt-$src.tgz", s"$tgt-$src.tgz")) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((IWSLT17Loader.Train, File(downloadsDir) / IWSLT17Loader.filename / IWSLT17Loader.filename / s"train.tags.$src-$tgt.$src", File(downloadsDir) / IWSLT17Loader.filename / IWSLT17Loader.filename / s"train.tags.$src-$tgt.$tgt", TEDConverter >> Normalizer)) case Dev => Seq((IWSLT17Loader.Dev2010, File(downloadsDir) / IWSLT17Loader.filename / IWSLT17Loader.filename / s"IWSLT17.TED.dev2010.$src-$tgt.$src.xml", File(downloadsDir) / IWSLT17Loader.filename / IWSLT17Loader.filename / s"IWSLT17.TED.dev2010.$src-$tgt.$tgt.xml", SGMConverter >> Normalizer)) case Test => Seq( (IWSLT17Loader.Test2010, File(downloadsDir) / IWSLT17Loader.filename / IWSLT17Loader.filename / s"IWSLT17.TED.tst2010.$src-$tgt.$src.xml", File(downloadsDir) / IWSLT17Loader.filename / IWSLT17Loader.filename / s"IWSLT17.TED.tst2010.$src-$tgt.$tgt.xml", SGMConverter >> Normalizer), (IWSLT17Loader.Test2017, File(downloadsDir) / s"$src-$tgt" / s"$src-$tgt" / s"IWSLT17.TED.tst2017.mltlng.$src-$tgt.$src.xml", File(downloadsDir) / s"$tgt-$src" / s"$tgt-$src" / s"IWSLT17.TED.tst2017.mltlng.$tgt-$src.$tgt.xml", SGMConverter >> Normalizer)) } } } object IWSLT17Loader { val url : String = "https://wit3.fbk.eu/archive/2017-01-trnmted/texts/DeEnItNlRo/DeEnItNlRo" val testUrl : String = "https://wit3.fbk.eu/archive/2017-01-mted-test/texts" val filename: String = "DeEnItNlRo-DeEnItNlRo" val supportedLanguagePairs: Set[(Language, Language)] = Set( (German, English), (German, Italian), (German, Dutch), (German, Romanian), (English, German), (English, Italian), (English, Dutch), (English, Romanian), (Italian, German), (Italian, English), (Italian, Dutch), (Italian, Romanian), (Dutch, German), (Dutch, Italian), (Dutch, English), (Dutch, Romanian), (Romanian, German), (Romanian, Italian), (Romanian, Dutch), (Romanian, English)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): IWSLT17Loader = { new IWSLT17Loader(srcLanguage, tgtLanguage, dataConfig) } trait Tag extends ParallelDataset.Tag object Tag { @throws[IllegalArgumentException] def fromName(name: String): Tag = name match { case "train" => Train case "dev2010" => Dev2010 case "tst2010" => Test2010 case "tst2017" => Test2017 case _ => throw new IllegalArgumentException(s"'$name' is not a valid IWSLT-17 tag.") } } case object Train extends Tag { override val value: String = "train" } case object Dev2010 extends Tag { override val value: String = "dev2010" } case object Test2010 extends Tag { override val value: String = "tst2010" } case object Test2017 extends Tag { override val value: String = "tst2017" } }
5,464
38.890511
125
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/CommonCrawlLoader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors.{FileProcessor, Normalizer} import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class CommonCrawlLoader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage = srcLanguage, tgtLanguage = tgtLanguage) { require( CommonCrawlLoader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the CommonCrawl dataset.") override def name: String = "CommonCrawl" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("commoncrawl") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("commoncrawl").resolve("downloads") private[this] def reversed: Boolean = { CommonCrawlLoader.supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } private[this] def corpusFilenamePrefix: String = { s"commoncrawl.${if (reversed) s"$tgt-$src" else s"$src-$tgt"}" } /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = Seq( (s"${CommonCrawlLoader.url}/${CommonCrawlLoader.archivePrefix}.tgz", s"${CommonCrawlLoader.archivePrefix}.tgz")) /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((CommonCrawlLoader.Train, File(downloadsDir) / CommonCrawlLoader.archivePrefix / s"$corpusFilenamePrefix.$src", File(downloadsDir) / CommonCrawlLoader.archivePrefix / s"$corpusFilenamePrefix.$tgt", Normalizer)) case _ => Seq.empty } } } object CommonCrawlLoader { val url : String = "http://www.statmt.org/wmt13" val archivePrefix: String = "training-parallel-commoncrawl" val supportedLanguagePairs: Set[(Language, Language)] = Set( (Czech, English), (French, English), (German, English), (Russian, English), (Spanish, English)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): CommonCrawlLoader = { new CommonCrawlLoader(srcLanguage, tgtLanguage, dataConfig) } case object Train extends ParallelDataset.Tag { override val value: String = "commoncrawl/train" } }
3,648
35.858586
116
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/IWSLT15Loader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors._ import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class IWSLT15Loader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage, tgtLanguage) { require( IWSLT15Loader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the IWSLT-15 dataset.") override def name: String = "IWSLT-15" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("iwslt-15") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("iwslt-15").resolve("downloads") private[this] def directoryName: String = s"$src-$tgt" /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq((s"${IWSLT15Loader.url}/$src/$tgt/$directoryName.tgz", s"$directoryName.tgz")) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((IWSLT15Loader.Train, File(downloadsDir) / directoryName / directoryName / s"train.tags.$directoryName.$src", File(downloadsDir) / directoryName / directoryName / s"train.tags.$directoryName.$tgt", TEDConverter >> Normalizer)) case Dev => Seq((IWSLT15Loader.Dev2010, File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.dev2010.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.dev2010.$directoryName.$tgt.xml", SGMConverter >> Normalizer)) case Test => Seq( (IWSLT15Loader.Test2010, File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.tst2010.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.tst2010.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT15Loader.Test2011, File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.tst2011.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.tst2011.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT15Loader.Test2012, File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.tst2012.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.tst2012.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT15Loader.Test2013, File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.tst2013.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT15.TED.tst2013.$directoryName.$tgt.xml", SGMConverter >> Normalizer)) } } } object IWSLT15Loader { val url: String = "https://wit3.fbk.eu/archive/2015-01/texts" val supportedLanguagePairs: Set[(Language, Language)] = Set( (English, Czech), (English, German), (English, French), (English, Thai), (English, Vietnamese), (English, Chinese), (Czech, English), (German, English), (French, English), (Thai, English), (Vietnamese, English), (Chinese, English)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): IWSLT15Loader = { new IWSLT15Loader(srcLanguage, tgtLanguage, dataConfig) } trait Tag extends ParallelDataset.Tag object Tag { @throws[IllegalArgumentException] def fromName(name: String): Tag = name match { case "train" => Train case "dev2010" => Dev2010 case "tst2010" => Test2010 case "tst2011" => Test2011 case "tst2012" => Test2012 case "tst2013" => Test2013 case _ => throw new IllegalArgumentException(s"'$name' is not a valid IWSLT-15 tag.") } } case object Train extends Tag { override val value: String = "train" } case object Dev2010 extends Tag { override val value: String = "dev2010" } case object Test2010 extends Tag { override val value: String = "tst2010" } case object Test2011 extends Tag { override val value: String = "tst2011" } case object Test2012 extends Tag { override val value: String = "tst2012" } case object Test2013 extends Tag { override val value: String = "tst2013" } }
5,776
37.771812
119
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/EuroparlV7Loader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors.{FileProcessor, Normalizer} import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class EuroparlV7Loader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage = srcLanguage, tgtLanguage = tgtLanguage) { require( EuroparlV7Loader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the Europarl v7 dataset.") override def name: String = "Europarl v7" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("europarl-v7") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("europarl-v7").resolve("downloads") private[this] def reversed: Boolean = { EuroparlV7Loader.supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } private[this] def corpusArchiveFile: String = if (reversed) s"$tgt-$src" else s"$src-$tgt" private[this] def corpusFilenamePrefix: String = { s"europarl-v7.${if (reversed) s"$tgt-$src" else s"$src-$tgt"}" } /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq((s"${EuroparlV7Loader.url}/$corpusArchiveFile.tgz", s"$corpusArchiveFile.tgz")) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((EuroparlV7Loader.Train, File(downloadsDir) / corpusArchiveFile / s"$corpusFilenamePrefix.$src", File(downloadsDir) / corpusArchiveFile / s"$corpusFilenamePrefix.$tgt", Normalizer)) case _ => Seq.empty } } } object EuroparlV7Loader { val url: String = "http://www.statmt.org/europarl/v7" val supportedLanguagePairs: Set[(Language, Language)] = Set( (Bulgarian, English), (Czech, English), (Danish, English), (Dutch, English), (Estonian, English), (Finnish, English), (French, English), (German, English), (Greek, English), (Hungarian, English), (Italian, English), (Lithuanian, English), (Latvian, English), (Polish, English), (Portuguese, English), (Romanian, English), (Slovak, English), (Slovenian, English), (Spanish, English), (Swedish, English)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): EuroparlV7Loader = { new EuroparlV7Loader(srcLanguage, tgtLanguage, dataConfig) } case object Train extends ParallelDataset.Tag { override val value: String = "europarl-v7/train" } }
3,932
36.817308
108
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/IWSLT16Loader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors._ import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class IWSLT16Loader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage, tgtLanguage) { require( IWSLT16Loader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the IWSLT-16 dataset.") override def name: String = "IWSLT-16" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("iwslt-16") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("iwslt-16").resolve("downloads") private[this] def directoryName: String = s"$src-$tgt" /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq( (s"${IWSLT16Loader.url}/texts/$src/$tgt/$directoryName.tgz", s"$directoryName.tgz"), (s"${IWSLT16Loader.url}-test/texts/$src/$tgt/$directoryName.tgz", s"$directoryName-test.tgz"), (s"${IWSLT16Loader.url}-test/texts/$tgt/$src/$tgt-$src.tgz", s"$tgt-$src-test.tgz")) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((IWSLT16Loader.Train, File(downloadsDir) / directoryName / directoryName / s"train.tags.$directoryName.$src", File(downloadsDir) / directoryName / directoryName / s"train.tags.$directoryName.$tgt", TEDConverter >> Normalizer)) case Dev => Seq((IWSLT16Loader.Dev2010, File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.dev2010.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.dev2010.$directoryName.$tgt.xml", SGMConverter >> Normalizer)) case Test => Seq( (IWSLT16Loader.Test2010, File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2010.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2010.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT16Loader.Test2011, File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2011.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2011.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT16Loader.Test2012, File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2012.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2012.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT16Loader.Test2013, File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2013.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2013.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT16Loader.Test2014, File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2014.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT16.TED.tst2014.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT16Loader.Test2015, File(downloadsDir) / s"$src-$tgt-test" / s"$src-$tgt" / s"IWSLT16.TED.tst2015.$src-$tgt.$src.xml", File(downloadsDir) / s"$tgt-$src-test" / s"$tgt-$src" / s"IWSLT16.TED.tst2015.$tgt-$src.$tgt.xml", SGMConverter >> Normalizer), (IWSLT16Loader.Test2016, File(downloadsDir) / s"$src-$tgt-test" / s"$src-$tgt" / s"IWSLT16.TED.tst2016.$src-$tgt.$src.xml", File(downloadsDir) / s"$tgt-$src-test" / s"$tgt-$src" / s"IWSLT16.TED.tst2016.$tgt-$src.$tgt.xml", SGMConverter >> Normalizer)) } }} object IWSLT16Loader { val url: String = "https://wit3.fbk.eu/archive/2016-01" val supportedLanguagePairs: Set[(Language, Language)] = Set( (English, Arabic), (English, Czech), (English, German), (English, French), (Arabic, English), (Czech, English), (German, English), (French, English)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): IWSLT16Loader = { new IWSLT16Loader(srcLanguage, tgtLanguage, dataConfig) } trait Tag extends ParallelDataset.Tag object Tag { @throws[IllegalArgumentException] def fromName(name: String): Tag = name match { case "train" => Train case "dev2010" => Dev2010 case "tst2010" => Test2010 case "tst2011" => Test2011 case "tst2012" => Test2012 case "tst2013" => Test2013 case "tst2014" => Test2014 case "tst2015" => Test2015 case "tst2016" => Test2016 case _ => throw new IllegalArgumentException(s"'$name' is not a valid IWSLT-16 tag.") } } case object Train extends Tag { override val value: String = "train" } case object Dev2010 extends Tag { override val value: String = "dev2010" } case object Test2010 extends Tag { override val value: String = "tst2010" } case object Test2011 extends Tag { override val value: String = "tst2011" } case object Test2012 extends Tag { override val value: String = "tst2012" } case object Test2013 extends Tag { override val value: String = "tst2013" } case object Test2014 extends Tag { override val value: String = "tst2014" } case object Test2015 extends Tag { override val value: String = "tst2015" } case object Test2016 extends Tag { override val value: String = "tst2016" } }
7,138
39.106742
112
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/EuroparlV8Loader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors.{FileProcessor, Normalizer} import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class EuroparlV8Loader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage = srcLanguage, tgtLanguage = tgtLanguage) { require( EuroparlV8Loader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the Europarl v8 dataset.") override def name: String = "Europarl v8" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("europarl-v8") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("europarl-v8").resolve("downloads") private[this] def reversed: Boolean = { EuroparlV8Loader.supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } private[this] def corpusFilenamePrefix: String = { s"europarl-v8.${if (reversed) s"$tgt-$src" else s"$src-$tgt"}" } /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq((s"${EuroparlV8Loader.url}/${EuroparlV8Loader.archivePrefix}.tgz", s"${EuroparlV8Loader.archivePrefix}.tgz")) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((EuroparlV8Loader.Train, File(downloadsDir) / EuroparlV8Loader.archivePrefix / EuroparlV8Loader.archivePrefix / s"$corpusFilenamePrefix.$src", File(downloadsDir) / EuroparlV8Loader.archivePrefix / EuroparlV8Loader.archivePrefix / s"$corpusFilenamePrefix.$tgt", Normalizer)) case _ => Seq.empty } } } object EuroparlV8Loader { val url : String = "http://data.statmt.org/wmt16/translation-task" val archivePrefix: String = "training-parallel-ep-v8" val supportedLanguagePairs: Set[(Language, Language)] = Set((Finnish, English), (Romanian, English)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): EuroparlV8Loader = { new EuroparlV8Loader(srcLanguage, tgtLanguage, dataConfig) } case object Train extends ParallelDataset.Tag { override val value: String = "europarl-v8/train" } }
3,687
35.514851
117
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/NewsCommentaryV11Loader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors._ import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class NewsCommentaryV11Loader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage = srcLanguage, tgtLanguage = tgtLanguage) { require( NewsCommentaryV11Loader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the News Commentary v11 dataset.") override def name: String = "News Commentary v11" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("news-commentary-v11") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("news-commentary-v11").resolve("downloads") private[this] def reversed: Boolean = { NewsCommentaryV11Loader.supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } private[this] def corpusFilenamePrefix: String = { s"news-commentary-v11.${if (reversed) s"$tgt-$src" else s"$src-$tgt"}" } /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq( (s"${NewsCommentaryV11Loader.url}/${NewsCommentaryV11Loader.archivePrefix}.tgz", s"${NewsCommentaryV11Loader.archivePrefix}.tgz")) } /** Returns all the corpora (tuples containing name, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => Seq((NewsCommentaryV11Loader.Train, File(downloadsDir) / NewsCommentaryV11Loader.archivePrefix / NewsCommentaryV11Loader.archivePrefix / s"$corpusFilenamePrefix.$src", File(downloadsDir) / NewsCommentaryV11Loader.archivePrefix / NewsCommentaryV11Loader.archivePrefix / s"$corpusFilenamePrefix.$tgt", Normalizer)) case _ => Seq.empty } } } object NewsCommentaryV11Loader { val url : String = "http://data.statmt.org/wmt16/translation-task" val archivePrefix: String = "training-parallel-nc-v11" val supportedLanguagePairs: Set[(Language, Language)] = { Set((Czech, English), (German, English), (Russian, English)) } def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): NewsCommentaryV11Loader = { new NewsCommentaryV11Loader(srcLanguage, tgtLanguage, dataConfig) } case object Train extends ParallelDataset.Tag { override val value: String = "news-commentary-v11/train" } }
3,852
35.695238
109
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/IWSLT14Loader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors._ import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class IWSLT14Loader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage, tgtLanguage) { require( IWSLT14Loader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the IWSLT-14 dataset.") override def name: String = "IWSLT-14" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("iwslt-14") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("iwslt-14").resolve("downloads") private[this] def directoryName: String = s"$src-$tgt" /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { Seq((s"${IWSLT14Loader.url}/$src/$tgt/$directoryName.tgz", s"$directoryName.tgz")) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { // TODO: !!! [DATA] Some of the tags are not supported for all language pairs. datasetType match { case Train => Seq((IWSLT14Loader.Train, File(downloadsDir) / directoryName / directoryName / s"train.tags.$directoryName.$src", File(downloadsDir) / directoryName / directoryName / s"train.tags.$directoryName.$tgt", TEDConverter >> Normalizer)) case Dev => Seq((IWSLT14Loader.Dev2010, File(downloadsDir) / directoryName / directoryName / s"IWSLT14.TED.dev2010.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT14.TED.dev2010.$directoryName.$tgt.xml", SGMConverter >> Normalizer)) case Test => Seq( (IWSLT14Loader.Test2010, File(downloadsDir) / directoryName / directoryName / s"IWSLT14.TED.tst2010.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT14.TED.tst2010.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT14Loader.Test2011, File(downloadsDir) / directoryName / directoryName / s"IWSLT14.TED.tst2011.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT14.TED.tst2011.$directoryName.$tgt.xml", SGMConverter >> Normalizer), (IWSLT14Loader.Test2012, File(downloadsDir) / directoryName / directoryName / s"IWSLT14.TED.tst2012.$directoryName.$src.xml", File(downloadsDir) / directoryName / directoryName / s"IWSLT14.TED.tst2012.$directoryName.$tgt.xml", SGMConverter >> Normalizer)) } } } object IWSLT14Loader { val url: String = "https://wit3.fbk.eu/archive/2014-01/texts" val supportedLanguagePairs: Set[(Language, Language)] = Set( (English, Arabic), (English, German), (English, Spanish), (English, Persian), (English, French), (English, Hebrew), (English, Italian), (English, Dutch), (English, Polish), (English, PortugueseBrazil), (English, Romanian), (English, Russian), (English, Slovenian), (English, Turkish), (English, Chinese), (Arabic, English), (German, English), (Spanish, English), (Persian, English), (French, English), (Hebrew, English), (Italian, English), (Dutch, English), (Polish, English), (PortugueseBrazil, English), (Romanian, English), (Russian, English), (Slovenian, English), (Turkish, English), (Chinese, English)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): IWSLT14Loader = { new IWSLT14Loader(srcLanguage, tgtLanguage, dataConfig) } trait Tag extends ParallelDataset.Tag object Tag { @throws[IllegalArgumentException] def fromName(name: String): Tag = name match { case "train" => Train case "dev2010" => Dev2010 case "tst2010" => Test2010 case "tst2011" => Test2011 case "tst2012" => Test2012 case _ => throw new IllegalArgumentException(s"'$name' is not a valid IWSLT-14 tag.") } } case object Train extends Tag { override val value: String = "train" } case object Dev2010 extends Tag { override val value: String = "dev2010" } case object Test2010 extends Tag { override val value: String = "tst2010" } case object Test2011 extends Tag { override val value: String = "tst2011" } case object Test2012 extends Tag { override val value: String = "tst2012" } }
5,835
39.248276
119
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/loaders/WMT16Loader.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.loaders import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data._ import org.platanios.symphony.mt.data.processors._ import better.files._ import java.nio.file.Path /** * @author Emmanouil Antonios Platanios */ class WMT16Loader( override val srcLanguage: Language, override val tgtLanguage: Language, val config: DataConfig ) extends ParallelDatasetLoader(srcLanguage = srcLanguage, tgtLanguage = tgtLanguage) { require( WMT16Loader.isLanguagePairSupported(srcLanguage, tgtLanguage), "The provided language pair is not supported by the WMT16 dataset.") override def name: String = "WMT-16" override def dataConfig: DataConfig = { config.copy(dataDir = config.dataDir .resolve("wmt-16") .resolve(s"${srcLanguage.abbreviation}-${tgtLanguage.abbreviation}")) } override def downloadsDir: Path = config.dataDir.resolve("wmt-16").resolve("downloads") private[this] def reversed: Boolean = { WMT16Loader.supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } protected def commonCrawlDataset: Option[CommonCrawlLoader] = { if (CommonCrawlLoader.isLanguagePairSupported(srcLanguage, tgtLanguage)) Some(CommonCrawlLoader(srcLanguage, tgtLanguage, dataConfig.copy(dataDir = config.dataDir))) else None } protected def europarlV7Dataset: Option[EuroparlV7Loader] = { if (EuroparlV7Loader.isLanguagePairSupported(srcLanguage, tgtLanguage)) Some(EuroparlV7Loader(srcLanguage, tgtLanguage, dataConfig.copy(dataDir = config.dataDir))) else None } protected def europarlV8Dataset: Option[EuroparlV8Loader] = { if (EuroparlV8Loader.isLanguagePairSupported(srcLanguage, tgtLanguage)) Some(EuroparlV8Loader(srcLanguage, tgtLanguage, dataConfig.copy(dataDir = config.dataDir))) else None } protected def newsCommentaryV11Dataset: Option[NewsCommentaryV11Loader] = { if (NewsCommentaryV11Loader.isLanguagePairSupported(srcLanguage, tgtLanguage)) Some(NewsCommentaryV11Loader(srcLanguage, tgtLanguage, dataConfig.copy(dataDir = config.dataDir))) else None } // TODO: Add support for the "CzEng 1.6pre" dataset. // TODO: Add support for the "Yandex Corpus" dataset. // TODO: Add support for the "Wiki Headlines" dataset. // TODO: Add support for the "SETIMES2" dataset. /** Sequence of files to download as part of this dataset. */ override def filesToDownload: Seq[(String, String)] = { (WMT16Loader.devArchives.map(archive => s"${WMT16Loader.newsCommentaryUrl}/$archive.tgz") ++ WMT16Loader.testArchives.map(archive => s"${WMT16Loader.newsCommentaryUrl}/$archive.tgz")) .map(url => (url, url.splitAt(url.lastIndexOf('/') + 1)._2)) } /** Returns all the corpora (tuples containing tag, source file, target file, and a file processor to use) * of this dataset type. */ override def corpora(datasetType: DatasetType): Seq[(ParallelDataset.Tag, File, File, FileProcessor)] = { datasetType match { case Train => commonCrawlDataset.map(_.corpora(Train)).getOrElse(Seq.empty) ++ europarlV7Dataset.map(_.corpora(Train)).getOrElse(Seq.empty) ++ europarlV8Dataset.map(_.corpora(Train)).getOrElse(Seq.empty) ++ newsCommentaryV11Dataset.map(_.corpora(Train)).getOrElse(Seq.empty) case Dev => WMT16Loader.devArchives.foreach(archive => { (File(downloadsDir) / archive) .copyTo(File(downloadsDir) / "dev", overwrite = true) }) var corpora = Seq.empty[(ParallelDataset.Tag, File, File, FileProcessor)] val supported2008Languages = Set[Language](Czech, English, French, German, Hungarian, Spanish) if (supported2008Languages.contains(srcLanguage) && supported2008Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2008, File(downloadsDir) / "dev" / "dev" / s"news-test2008-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"news-test2008-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2009Languages = Set[Language](Czech, English, French, German, Hungarian, Italian, Spanish) if (supported2009Languages.contains(srcLanguage) && supported2009Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2009, File(downloadsDir) / "dev" / "dev" / s"newstest2009-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newstest2009-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2009SysCombLanguages = Set[Language](Czech, English, French, German, Hungarian, Italian, Spanish) if (supported2009SysCombLanguages.contains(srcLanguage) && supported2009SysCombLanguages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsSysComb2009, File(downloadsDir) / "dev" / "dev" / s"newssyscomb2009-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newssyscomb2009-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2010Languages = Set[Language](Czech, English, French, German, Spanish) if (supported2010Languages.contains(srcLanguage) && supported2010Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2010, File(downloadsDir) / "dev" / "dev" / s"newstest2010-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newstest2010-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2011Languages = Set[Language](Czech, English, French, German, Spanish) if (supported2011Languages.contains(srcLanguage) && supported2011Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2011, File(downloadsDir) / "dev" / "dev" / s"newstest2011-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newstest2011-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2012Languages = Set[Language](Czech, English, French, German, Russian, Spanish) if (supported2012Languages.contains(srcLanguage) && supported2012Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2012, File(downloadsDir) / "dev" / "dev" / s"newstest2012-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newstest2012-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2013Languages = Set[Language](Czech, English, French, German, Russian, Spanish) if (supported2013Languages.contains(srcLanguage) && supported2013Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2013, File(downloadsDir) / "dev" / "dev" / s"newstest2013-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newstest2013-ref.$tgt.sgm", SGMConverter >> Normalizer)) val pair = if (reversed) s"$tgt$src" else s"$src$tgt" val supported2014Languages = Set[Language](Czech, English, French, German, Hindi, Russian) if (supported2014Languages.contains(srcLanguage) && supported2014Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2014, File(downloadsDir) / "dev" / "dev" / s"newstest2014-$pair-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newstest2014-$pair-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2014DevLanguages = Set[Language](English, Hindi) if (supported2014DevLanguages.contains(srcLanguage) && supported2014DevLanguages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsDev2014, File(downloadsDir) / "dev" / "dev" / s"newsdev2014-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newsdev2014-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2015Languages = Set[Language](Czech, English, Finnish, German, Russian) if (supported2015Languages.contains(srcLanguage) && supported2015Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2015, File(downloadsDir) / "dev" / "dev" / s"newstest2015-$src$tgt-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newstest2015-$src$tgt-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2015DevLanguages = Set[Language](English, Finnish) if (supported2015DevLanguages.contains(srcLanguage) && supported2015DevLanguages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsDev2015, File(downloadsDir) / "dev" / "dev" / s"newsdev2015-$src$tgt-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newsdev2015-$src$tgt-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2015DiscussDevLanguages = Set[Language](English, French) if (supported2015DiscussDevLanguages.contains(srcLanguage) && supported2015DiscussDevLanguages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsDiscussDev2015, File(downloadsDir) / "dev" / "dev" / s"newsdiscussdev2015-$src$tgt-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newsdiscussdev2015-$src$tgt-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2015DiscussTestLanguages = Set[Language](English, French) if (supported2015DiscussTestLanguages.contains(srcLanguage) && supported2015DiscussTestLanguages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsDiscussTest2015, File(downloadsDir) / "dev" / "dev" / s"newsdiscusstest2015-$src$tgt-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newsdiscusstest2015-$src$tgt-ref.$tgt.sgm", SGMConverter >> Normalizer)) val supported2016DevLanguages = Set[Language](English, Romanian, Turkish) if (supported2016DevLanguages.contains(srcLanguage) && supported2016DevLanguages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsDev2016, File(downloadsDir) / "dev" / "dev" / s"newsdev2016-$src$tgt-src.$src.sgm", File(downloadsDir) / "dev" / "dev" / s"newsdev2016-$src$tgt-ref.$tgt.sgm", SGMConverter >> Normalizer)) corpora case Test => WMT16Loader.testArchives.foreach(archive => { (File(downloadsDir) / archive) .copyTo(File(downloadsDir) / "test", overwrite = true) }) var corpora = Seq.empty[(ParallelDataset.Tag, File, File, FileProcessor)] val supported2016Languages = Set[Language](Czech, English, Finnish, German, Romanian, Russian, Turkish) if (supported2016Languages.contains(srcLanguage) && supported2016Languages.contains(tgtLanguage)) corpora ++= Seq((WMT16Loader.NewsTest2016, File(downloadsDir) / "test" / "test" / s"newstest2016-$src$tgt-src.$src.sgm", File(downloadsDir) / "test" / "test" / s"newstest2016-$src$tgt-ref.$tgt.sgm", SGMConverter >> Normalizer)) corpora } } } object WMT16Loader { val newsCommentaryUrl : String = "http://data.statmt.org/wmt16/translation-task" val newsCommentaryParallelArchive: String = "training-parallel-nc-v11" val devArchives : Seq[String] = Seq("dev", "dev-romanian-updated") val testArchives : Seq[String] = Seq("test") val supportedLanguagePairs: Set[(Language, Language)] = Set( (Czech, English), (Finnish, English), (German, English), (Romanian, English), (Russian, English), (Turkish, English)) def isLanguagePairSupported(srcLanguage: Language, tgtLanguage: Language): Boolean = { supportedLanguagePairs.contains((srcLanguage, tgtLanguage)) || supportedLanguagePairs.contains((tgtLanguage, srcLanguage)) } def apply( srcLanguage: Language, tgtLanguage: Language, dataConfig: DataConfig ): WMT16Loader = { new WMT16Loader(srcLanguage, tgtLanguage, dataConfig) } trait Tag extends ParallelDataset.Tag object Tag { @throws[IllegalArgumentException] def fromName(name: String): Tag = name match { case "newstest2008" => NewsTest2008 case "newstest2009" => NewsTest2009 case "newssyscomb2009" => NewsSysComb2009 case "newstest2010" => NewsTest2010 case "newstest2011" => NewsTest2011 case "newstest2012" => NewsTest2012 case "newstest2013" => NewsTest2013 case "newstest2014" => NewsTest2014 case "newsdev2014" => NewsDev2014 case "newstest2015" => NewsTest2015 case "newsdev2015" => NewsDev2015 case "newsdiscussdev2015" => NewsDiscussDev2015 case "newsdiscusstest2015" => NewsDiscussTest2015 case "newsdev2016" => NewsDev2016 case "newstest2016" => NewsTest2016 case _ => throw new IllegalArgumentException(s"'$name' is not a valid WMT-16 tag.") } } case object NewsTest2008 extends Tag { override val value: String = "newstest2008" } case object NewsTest2009 extends Tag { override val value: String = "newstest2009" } case object NewsSysComb2009 extends Tag { override val value: String = "newssyscomb2009" } case object NewsTest2010 extends Tag { override val value: String = "newstest2010" } case object NewsTest2011 extends Tag { override val value: String = "newstest2011" } case object NewsTest2012 extends Tag { override val value: String = "newstest2012" } case object NewsTest2013 extends Tag { override val value: String = "newstest2013" } case object NewsTest2014 extends Tag { override val value: String = "newstest2014" } case object NewsDev2014 extends Tag { override val value: String = "newsdev2014" } case object NewsTest2015 extends Tag { override val value: String = "newstest2015" } case object NewsDev2015 extends Tag { override val value: String = "newsdev2015" } case object NewsDiscussDev2015 extends Tag { override val value: String = "newsdiscussdev2015" } case object NewsDiscussTest2015 extends Tag { override val value: String = "newsdiscusstest2015" } case object NewsDev2016 extends Tag { override val value: String = "newsdev2016" } case object NewsTest2016 extends Tag { override val value: String = "newstest2016" } }
15,158
46.224299
119
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/scores/WordCounts.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.scores import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{newReader, newWriter} import org.platanios.symphony.mt.utilities.TrieWordCounter import better.files._ import scala.collection.mutable import scala.util.matching.Regex /** * @author Emmanouil Antonios Platanios */ class WordCounts(val caseSensitive: Boolean = false) extends SummaryScore { protected val whitespaceRegex: Regex = "\\s+".r protected val counters: mutable.HashMap[Language, TrieWordCounter] = { mutable.HashMap.empty[Language, TrieWordCounter] } override def name: String = { if (caseSensitive) "cs-wc" else "wc" } override def processSentence( language: Language, sentence: String, requiredValues: Seq[Float], requiredSummaries: Seq[SummaryScore] ): Unit = { whitespaceRegex.split(sentence).foreach(word => { if (caseSensitive) counters.getOrElseUpdate(language, TrieWordCounter()).insertWord(word) else counters.getOrElseUpdate(language, TrieWordCounter()).insertWord(word.toLowerCase) }) } override def resetState(): Unit = { counters.clear() } override def saveStateToFile(file: File): Unit = { val writer = newWriter(file) counters.foreach { case (language, counter) => writer.write(s"${WordCounts.FILE_LANGUAGE_SEPARATOR}\n") writer.write(s"${language.name}\n") for ((count, word) <- counter.words().toSeq.sortBy(-_._1).distinct) writer.write(s"$word\t$count\n") } writer.flush() writer.close() } override def loadStateFromFile(file: File): Unit = { reset() var currentLanguage: Option[Language] = None newReader(file).lines().toAutoClosedIterator.foreach(line => { if (line == WordCounts.FILE_LANGUAGE_SEPARATOR) { currentLanguage = None } else { currentLanguage match { case None => currentLanguage = Some(Language.fromName(line)) case Some(language) => val lineParts = line.split('\t') counters.getOrElseUpdate(language, TrieWordCounter()) .insertWordWithCount(word = lineParts(0), count = lineParts(1).toLong) } } }) } def count(language: Language, word: String): Long = { counters(language)(word) } def totalCount(language: Language): Long = { counters(language).totalCount } } object WordCounts { private[WordCounts] val FILE_LANGUAGE_SEPARATOR: String = "-" * 100 def apply(caseSensitive: Boolean = false): WordCounts = { new WordCounts(caseSensitive) } }
3,268
29.839623
90
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/scores/SentenceRarity.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.scores import org.platanios.symphony.mt.Language import scala.util.matching.Regex /** * @author Emmanouil Antonios Platanios */ class SentenceRarity( val wordFrequenciesPooling: SentenceRarity.WordFrequenciesPooling, val wordCounts: WordCounts = WordCounts(caseSensitive = false), val epsilon: Double = 1e-3f ) extends SentenceScore { override def name: String = { s"sr-$wordFrequenciesPooling-$wordCounts" } override def requiredSummaryScores: Seq[SummaryScore] = { Seq(wordCounts) } override def processSentence( language: Language, sentence: String, requiredValues: Seq[Float], requiredSummaries: Seq[SummaryScore] ): Float = { val logTotalCount = math.log(wordCounts.totalCount(language).toDouble) val counts = SentenceRarity.whitespaceRegex.split(sentence).map(word => { val count = wordCounts.count(language, word).toDouble if (count == 0.0) epsilon else count }) val logFrequencies = counts.map(math.log(_) - logTotalCount) -wordFrequenciesPooling(logFrequencies, logFrequencies = true).toFloat } } object SentenceRarity { protected[SentenceRarity] val whitespaceRegex: Regex = "\\s+".r def apply( wordFrequenciesPooling: WordFrequenciesPooling, wordCounts: WordCounts = WordCounts(caseSensitive = false), epsilon: Double = 1e-3f ): SentenceRarity = { new SentenceRarity(wordFrequenciesPooling, wordCounts, epsilon) } trait WordFrequenciesPooling { def apply(frequencies: Seq[Double], logFrequencies: Boolean): Double override def toString: String } case object MinPooling extends WordFrequenciesPooling { override def apply(frequencies: Seq[Double], logFrequencies: Boolean): Double = { frequencies.min } override def toString: String = { "min" } } case object MaxPooling extends WordFrequenciesPooling { override def apply(frequencies: Seq[Double], logFrequencies: Boolean): Double = { frequencies.max } override def toString: String = { "max" } } case object MeanPooling extends WordFrequenciesPooling { override def apply(frequencies: Seq[Double], logFrequencies: Boolean): Double = { if (logFrequencies) logSumExp(frequencies) else frequencies.sum / frequencies.size.toDouble } override def toString: String = { "mean" } } case object ProductPooling extends WordFrequenciesPooling { override def apply(frequencies: Seq[Double], logFrequencies: Boolean): Double = { if (logFrequencies) frequencies.sum else frequencies.product } override def toString: String = { "prod" } } private def logSumExp(a: Double, b: Double): Double = { if (a == Double.NegativeInfinity) b else if (b == Double.NegativeInfinity) a else if (a < b) b + math.log(1 + math.exp(a - b)) else a + math.log(1 + math.exp(b - a)) } private def logSumExp(values: Seq[Double]): Double = { values.length match { case 0 => Double.NegativeInfinity case 1 => values(0) case 2 => logSumExp(values(0), values(1)) case _ => val max = values.max if (max.isInfinite) max else max + math.log(values.map(_ - max).sum) } } }
3,991
27.927536
85
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/scores/SentenceLength.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.scores import org.platanios.symphony.mt.Language import scala.util.matching.Regex /** * @author Emmanouil Antonios Platanios */ object SentenceLength extends SentenceScore { protected val whitespaceRegex: Regex = "\\s+".r override def name: String = { "sl" } override def processSentence( language: Language, sentence: String, requiredValues: Seq[Float], requiredSummaries: Seq[SummaryScore] ): Float = { whitespaceRegex.split(sentence).length } }
1,176
27.707317
80
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/scores/SentenceScoreHistogram.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.scores import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{newReader, newWriter} import org.platanios.symphony.mt.utilities.Histogram import better.files._ import scala.collection.mutable // TODO: [DATA] [SCORES] Create a `LanguageSpecificSummaryScore` abstraction for this and the `WordCounts` summaries. /** * @author Emmanouil Antonios Platanios */ class SentenceScoreHistogram( val score: SentenceScore, val maxNumBins: Int, val languageSpecific: Boolean = true ) extends SummaryScore { protected val histograms: mutable.HashMap[Language, Histogram] = { mutable.HashMap.empty[Language, Histogram] } override def name: String = { s"$score.$maxNumBins.bins.histogram" } override def requiredSentenceScores: Seq[SentenceScore] = { Seq(score) } override def processSentence( language: Language, sentence: String, requiredValues: Seq[Float], requiredSummaries: Seq[SummaryScore] ): Unit = { val sentenceScore = score.processSentence(language, sentence, requiredValues, requiredSummaries) histogram(language).insert(sentenceScore) } def cdfScore: SentenceScore = { val histogramScore = this new SentenceScore { override def name: String = { s"$histogramScore.cdf" } override def requiredSentenceScores: Seq[SentenceScore] = { Seq(score) } override def requiredSummaryScores: Seq[SummaryScore] = { Seq(histogramScore) } override def processSentence( language: Language, sentence: String, requiredValues: Seq[Float], requiredSummaries: Seq[SummaryScore] ): Float = { histogramScore.histogram(language).cdf(requiredValues.head).toFloat } } } override def resetState(): Unit = { histograms.clear() } override def saveStateToFile(file: File): Unit = { val writer = newWriter(file) if (languageSpecific) { histograms.foreach { case (language, histogram) => writer.write(s"${SentenceScoreHistogram.FILE_LANGUAGE_SEPARATOR}\n") writer.write(s"${language.name}\n") histogram.bins.foreach(bin => { writer.write(s"${bin.mean}\t${bin.numSamples}\n") }) } } else { histograms.values.head.bins.foreach(bin => { writer.write(s"${bin.mean}\t${bin.numSamples}\n") }) } writer.flush() writer.close() } override def loadStateFromFile(file: File): Unit = { reset() if (languageSpecific) { var currentLanguage: Option[Language] = None newReader(file).lines().toAutoClosedIterator.foreach(line => { if (line == SentenceScoreHistogram.FILE_LANGUAGE_SEPARATOR) { currentLanguage = None } else { currentLanguage match { case None => currentLanguage = Some(Language.fromName(line)) case Some(language) => val lineParts = line.split('\t') histograms.getOrElseUpdate(language, Histogram(maxNumBins)) .insertBin(Histogram.Bin(mean = lineParts(0).toDouble, numSamples = lineParts(1).toLong)) } } }) } else { val histogram = Histogram(maxNumBins) newReader(file).lines().toAutoClosedIterator.foreach(line => { val lineParts = line.split('\t') histogram.insertBin(Histogram.Bin(mean = lineParts(0).toDouble, numSamples = lineParts(1).toLong)) }) histograms.update(null, histogram) } } /** Obtains the histogram to use for a specific language. */ protected def histogram(language: Language): Histogram = { if (languageSpecific) { histograms.getOrElseUpdate(language, Histogram(maxNumBins)) } else if (histograms.isEmpty) { histograms.getOrElseUpdate(language, Histogram(maxNumBins)) } else { // This is a little hack in case we are using the same histogram for all languages. histograms.values.head } } } object SentenceScoreHistogram { private[SentenceScoreHistogram] val FILE_LANGUAGE_SEPARATOR: String = "-" * 100 def apply( score: SentenceScore, maxNumBins: Int ): SentenceScoreHistogram = { new SentenceScoreHistogram(score, maxNumBins) } }
4,953
30.35443
117
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/scores/Score.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.scores import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{FileParallelDataset, newReader, newWriter} import org.platanios.symphony.mt.utilities.TopologicalSort import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import scala.collection.mutable /** * @author Emmanouil Antonios Platanios */ trait Score { type T val isSummary: Boolean def name: String def requiredSentenceScores: Seq[SentenceScore] = { Seq.empty } def requiredSummaryScores: Seq[SummaryScore] = { Seq.empty } def processSentence( language: Language, sentence: String, requiredValues: Seq[Float], requiredSummaries: Seq[SummaryScore] ): T override def toString: String = { name } } trait SentenceScore extends Score { override type T = Float override val isSummary: Boolean = false } trait SummaryScore extends Score { override type T = Unit override val isSummary: Boolean = true private[scores] def reset(): Unit = { resetState() } protected def resetState(): Unit def saveStateToFile(file: File): Unit def loadStateFromFile(file: File): Unit } object Score { private val logger = Logger(LoggerFactory.getLogger("Data / Scorer")) @throws[IllegalStateException] def scoreDatasets( datasets: Seq[FileParallelDataset], score: Score, scoresDir: File, alwaysRecompute: Boolean = false ): Unit = { val summaryScoresDir = scoresDir / "summary_scores" val sentenceScoresDir = scoresDir / "sentence_scores" summaryScoresDir.createDirectories() sentenceScoresDir.createDirectories() var computedSummaryScores = Set.empty[SummaryScore] var scores = TopologicalSort.sort[Score]( values = Set(score), requirements = (s: Score) => s.requiredSentenceScores.toSet ++ s.requiredSummaryScores.toSet ).getOrElse(throw new IllegalStateException("There should be no cycles in the scores dependencies.")) while (scores.nonEmpty) { val computingSummaryScore = scores.head.isSummary val scoresToCompute = { if (computingSummaryScore) { val summaryScore = scores.head.asInstanceOf[SummaryScore] summaryScore.reset() logger.info(s"Computing summary score '$summaryScore'.") Seq(summaryScore) } else { val sentenceScores = scores.takeWhile(!_.isSummary) logger.info(s"Computing sentence scores: ${sentenceScores.map(s => s"'$s'").mkString(", ")}.") sentenceScores } } val (summaryScoreFile, computeSummaryScore) = { if (computingSummaryScore) { val summaryScore = scoresToCompute.head.asInstanceOf[SummaryScore] val summaryScoreFile = summaryScoresDir / s"$summaryScore.score" if (alwaysRecompute || summaryScoreFile.notExists) { (summaryScoreFile, true) } else { (summaryScoreFile, false) } } else { (null, false) } } datasets.foreach(dataset => { dataset.files.foreach { case (language, files) => files.foreach(file => { val baseFilename = file.path.toAbsolutePath.normalize.toString.replace('/', '_') val scoreFiles = sentenceScoresDir.collectChildren(_.name.startsWith(baseFilename)).toArray val scoreNames = scoreFiles.map(_.name.drop(baseFilename.length + 1).dropRight(6)) val scoreValues = scoreFiles.map(file => { newReader(file).lines().toAutoClosedIterator.map(_.toFloat).toArray }) var sentenceScores = mutable.HashMap(scoreNames.zip(scoreValues): _*) if (computingSummaryScore) { val summaryScore = scoresToCompute.head.asInstanceOf[SummaryScore] if (computeSummaryScore) { val requiredSentenceScores = summaryScore.requiredSentenceScores.map(s => sentenceScores(s.toString)) val requiredSummaryScores = summaryScore.requiredSummaryScores.map(s => { computedSummaryScores.find(_ == s).get }) // Update the summary score using all sentences. newReader(file).lines().toAutoClosedIterator.zipWithIndex.foreach(sentence => { summaryScore.processSentence( language = language, sentence = sentence._1, requiredValues = requiredSentenceScores.map(_.apply(sentence._2)), requiredSummaries = requiredSummaryScores) }) } } else { // Determine which scores need to be computed/re-computed. val sentenceScoresToCompute = { if (alwaysRecompute) scoresToCompute else scoresToCompute.filter(s => !sentenceScores.contains(s.toString)) } if (sentenceScoresToCompute.nonEmpty) { logger.info(s"Computing sentence scores for file '$file'.") val fileSource = scala.io.Source.fromFile(file.path.toAbsolutePath.toString) val numSentences = fileSource.getLines.size fileSource.close() // Remove the previously computed values for the scores that need to be computed now. sentenceScores ++= sentenceScoresToCompute.map(_.toString) .zip(sentenceScoresToCompute.map(_ => Array.ofDim[Float](numSentences))) val scoresWithRequirements = sentenceScoresToCompute.map(score => { val requiredSentenceScores = score.requiredSentenceScores.map(s => sentenceScores(s.toString)) val requiredSummaryScores = score.requiredSummaryScores.map(s => { computedSummaryScores.find(_ == s).get }) (score, requiredSentenceScores, requiredSummaryScores) }) var progress = 0L var progressLogTime = System.currentTimeMillis // Compute the new scores for all sentences. newReader(file).lines().toAutoClosedIterator.zipWithIndex.foreach(sentence => { scoresWithRequirements.zipWithIndex.foreach(score => { val sentenceScore = score._1._1.processSentence( language = language, sentence = sentence._1, requiredValues = score._1._2.map(_.apply(sentence._2)), requiredSummaries = score._1._3) sentenceScores(score._1._1.toString)(sentence._2) = sentenceScore.asInstanceOf[Float] progress += 1 val time = System.currentTimeMillis if (time - progressLogTime >= 1e4) { val numBars = Math.floorDiv(10 * progress, numSentences).toInt logger.info( s"│${"═" * numBars}${" " * (10 - numBars)}│ " + s"%${numSentences.toString.length}s / $numSentences sentences done.".format(progress)) progressLogTime = time } }) }) sentenceScoresToCompute.foreach(score => { val file = sentenceScoresDir / s"$baseFilename.$score.score" val writer = newWriter(file) sentenceScores(score.toString).foreach(v => writer.write(s"$v\n")) writer.flush() writer.close() logger.info(s"Wrote sentence scores file '$file'.") }) } } }) } }) if (computingSummaryScore) { val summaryScore = scoresToCompute.head.asInstanceOf[SummaryScore] if (computeSummaryScore) { // Save state to file, if necessary. if (!summaryScoreFile.exists) summaryScoreFile.parent.createDirectories() summaryScore.saveStateToFile(summaryScoreFile) logger.info(s"Wrote summary scores file '$summaryScoreFile'.") } else { // Load state from file. summaryScore.loadStateFromFile(summaryScoreFile) } computedSummaryScores += summaryScore } scores = scores.drop(scoresToCompute.size) } } }
9,117
35.766129
117
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/Cleaner.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{newReader, newWriter} import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory /** * @author Emmanouil Antonios Platanios */ trait Cleaner extends FileProcessor { override def apply(file1: File, file2: File, language1: Language, language2: Language): (File, File) = { cleanCorporaPair(file1, file2) } def cleanFile(originalFile: File): File def cleanSentencePair(srcSentence: String, tgtSentence: String): Option[(String, String)] def cleanCorporaPair(srcFile: File, tgtFile: File, bufferSize: Int = 8192): (File, File) = { val srcClean = cleanFile(srcFile) val tgtClean = cleanFile(tgtFile) if (srcClean.notExists || tgtClean.notExists) { Cleaner.logger.info(s"Cleaning '$srcFile' and '$tgtFile'.") val srcWriter = newWriter(srcClean) val tgtWriter = newWriter(tgtClean) newReader(srcFile).lines().toAutoClosedIterator .zip(newReader(tgtFile).lines().toAutoClosedIterator).foreach(pair => { cleanSentencePair(pair._1, pair._2) match { case Some((srcSentence, tgtSentence)) if srcSentence.length > 0 && tgtSentence.length > 0 => srcWriter.write(s"$srcSentence\n") tgtWriter.write(s"$tgtSentence\n") case None => () } }) srcWriter.flush() srcWriter.close() tgtWriter.flush() tgtWriter.close() Cleaner.logger.info(s"Created clean files '$srcClean' and '$tgtClean'.") } (srcClean, tgtClean) } override def toString: String } object Cleaner { private[data] val logger = Logger(LoggerFactory.getLogger("Data / Cleaner")) }
2,402
34.865672
106
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/MosesTokenizer.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import better.files.File import scala.util.matching.Regex /** Tokenizer used by the Moses library. * * The code in this class is a Scala translation of the * [original Moses code](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/tokenizer.perl). * * @param aggressiveHyphenSplitting If `true`, hyphens will be aggressively split and replaced by `"@-@"` tokens. * @param escapeSpecialCharacters If `true`, various special characters (such as a double quote, for example) will * be escaped. * @param nonBreakingPrefixes Optional map containing non-breaking prefixes for each language. These are * prefixes that are not at the end of sentences (i.e., sentence-breaking). * * @author Emmanouil Antonios Platanios */ case class MosesTokenizer( aggressiveHyphenSplitting: Boolean = false, escapeSpecialCharacters: Boolean = true, nonBreakingPrefixes: Map[Language, MosesTokenizer.NonBreakingPrefixes] = MosesTokenizer.defaultNonBreakingPrefixes ) extends Tokenizer { private val ignoredRegex : Regex = """[\000-\037]""".r private val whitespaceRegex : Regex = """\s+""".r private val periodRegex : Regex = """\.""".r private val alphabeticRegex : Regex = """\p{IsAlpha}""".r private val notLowercaseRegex : Regex = """^[\p{IsLower}]""".r private val notDigitsRegex : Regex = """^[0-9]+""".r private val symbolsRegex : Regex = """([^\p{IsAlnum}\s\.\'\`\,\-])""".r private val fiSvColonRegex1 : Regex = """([^\p{IsAlnum}\s\.\:\'\`\,\-])""".r private val fiSvColonRegex2 : Regex = """(:)(?=$|[^\p{IsLl}])""".r private val aggressiveHyphenSplittingRegex: Regex = """([\p{IsAlnum}])\-(?=[\p{IsAlnum}])""".r private val multiDotRegex1 : Regex = """\.([\.]+)""".r private val multiDotRegex2 : Regex = """DOTMULTI\.""".r private val multiDotRegex3 : Regex = """DOTMULTI\.([^\.])""".r private val multiDotRegex4 : Regex = """DOTDOTMULTI""".r private val multiDotRegex5 : Regex = """DOTMULTI""".r private val commaRegex1 : Regex = """([^\p{IsDigit}])[,]""".r private val commaRegex2 : Regex = """[,]([^\p{IsDigit}])""".r private val enContractionsRegex1 : Regex = """([^\p{IsAlpha}])[']([^\p{IsAlpha}])""".r private val enContractionsRegex2 : Regex = """([^\p{IsAlpha}\p{IsDigit}])[']([\p{IsAlpha}])""".r private val enContractionsRegex3 : Regex = """([\p{IsAlpha}])[']([^\p{IsAlpha}])""".r private val enContractionsRegex4 : Regex = """([\p{IsAlpha}])[']([\p{IsAlpha}])""".r private val enContractionsRegex5 : Regex = """([\p{IsDigit}])[']([s])""".r private val frItGaContractionsRegex1 : Regex = """([^\p{IsAlpha}])[']([^\p{IsAlpha}])""".r private val frItGaContractionsRegex2 : Regex = """([^\p{IsAlpha}])[']([\p{IsAlpha}])""".r private val frItGaContractionsRegex3 : Regex = """([\p{IsAlpha}])[']([^\p{IsAlpha}])""".r private val frItGaContractionsRegex4 : Regex = """([\p{IsAlpha}])[']([\p{IsAlpha}])""".r private val otherContractionsRegex : Regex = """\'""".r private val wordRegex : Regex = """^(\S+)\.$""".r private val endOfSentenceRegex : Regex = """\.\' ?$""".r private val preEscapeRegex1 : Regex = """& amp ;""".r private val preEscapeRegex2 : Regex = """& #124 ;""".r private val preEscapeRegex3 : Regex = """& lt ;""".r private val preEscapeRegex4 : Regex = """& gt ;""".r private val preEscapeRegex5 : Regex = """& apos ;""".r private val preEscapeRegex6 : Regex = """& quot ;"""".r private val preEscapeRegex7 : Regex = """& #91 ;""".r private val preEscapeRegex8 : Regex = """& #93 ;""".r private val escapeRegex1 : Regex = """&(?!#?[a-zA-Z0-9]{2,7};)""".r private val escapeRegex2 : Regex = """\|""".r private val escapeRegex3 : Regex = """\<""".r private val escapeRegex4 : Regex = """\>""".r private val escapeRegex5 : Regex = """\'""".r private val escapeRegex6 : Regex = """\"""".r private val escapeRegex7 : Regex = """\[""".r private val escapeRegex8 : Regex = """\]""".r override def tokenizedFile(originalFile: File): File = { val fileName = originalFile.nameWithoutExtension(includeAll = false) originalFile.sibling(fileName + s".tok:moses${originalFile.extension().get}") } override def tokenize(sentence: String, language: Language): String = { var tokenized = sentence.trim // Remove ASCII junk characters. tokenized = whitespaceRegex.replaceAllIn(tokenized, " ") tokenized = ignoredRegex.replaceAllIn(tokenized, "") // Separate out all other special characters. if (language == Finnish || language == Swedish) { // In Finnish and Swedish, the colon can be used inside words as an apostrophe-like character. For example: // "USA:n", "20:een", "EU:ssa", "USA:s", "S:t", etc. tokenized = fiSvColonRegex1.replaceAllIn(tokenized, " $1 ") // If a colon is not immediately followed by lower-case characters, separate it out anyway. tokenized = fiSvColonRegex2.replaceAllIn(tokenized, " $1 ") } else { tokenized = symbolsRegex.replaceAllIn(tokenized, " $1 ") } // Aggressive hyphen splitting. if (aggressiveHyphenSplitting) tokenized = aggressiveHyphenSplittingRegex.replaceAllIn(tokenized, "$1 @-@ ") // Multi-dots stay together. tokenized = multiDotRegex1.replaceAllIn(tokenized, " DOTMULTI$1") while (multiDotRegex2.findFirstIn(tokenized).isDefined) { tokenized = multiDotRegex3.replaceAllIn(tokenized, "DOTDOTMULTI $1") tokenized = multiDotRegex2.replaceAllIn(tokenized, "DOTDOTMULTI") } // Separate out "," except if within numbers, and after a number if it's at the end of a sentence. tokenized = commaRegex1.replaceAllIn(tokenized, "$1 , ") tokenized = commaRegex2.replaceAllIn(tokenized, " , $1") // Handle contractions. if (language == English) { // Split contractions right. tokenized = enContractionsRegex1.replaceAllIn(tokenized, "$1 ' $2") tokenized = enContractionsRegex2.replaceAllIn(tokenized, "$1 ' $2") tokenized = enContractionsRegex3.replaceAllIn(tokenized, "$1 ' $2") tokenized = enContractionsRegex4.replaceAllIn(tokenized, "$1 '$2") // Special case for years, like "1990's". tokenized = enContractionsRegex5.replaceAllIn(tokenized, "$1 '$2") } else if (language == French || language == Italian || language == Irish) { // Split contractions left. tokenized = frItGaContractionsRegex1.replaceAllIn(tokenized, "$1 ' $2") tokenized = frItGaContractionsRegex2.replaceAllIn(tokenized, "$1 ' $2") tokenized = frItGaContractionsRegex3.replaceAllIn(tokenized, "$1 ' $2") tokenized = frItGaContractionsRegex4.replaceAllIn(tokenized, "$1' $2") } else { tokenized = otherContractionsRegex.replaceAllIn(tokenized, " ' ") } // Tokenize words. val words = whitespaceRegex.split(tokenized) tokenized = words.zipWithIndex.map(word => { val wordMatch = wordRegex.findFirstMatchIn(word._1) if (wordMatch.isEmpty) { word._1 } else { val prefix = wordMatch.get.group(1) if (periodRegex.findFirstIn(prefix).isDefined && alphabeticRegex.findFirstIn(prefix).isDefined || nonBreakingPrefixes(language).prefixes.contains(prefix) || word._2 < words.length - 1 && notLowercaseRegex.findFirstIn(words(word._2 + 1)).isDefined || (word._2 < words.length - 1 && notDigitsRegex.findFirstIn(words(word._2 + 1)).isDefined && nonBreakingPrefixes(language).numericPrefixes.contains(prefix))) { word._1 } else { s"$prefix ." } } }).mkString(" ") // Clean up extraneous spaces. tokenized = tokenized.trim tokenized = whitespaceRegex.replaceAllIn(tokenized, " ") // Fix ".'" at the end of the sentence. tokenized = endOfSentenceRegex.replaceFirstIn(tokenized, " . ' ") // Restore multi-dots. while (multiDotRegex4.findFirstIn(tokenized).isDefined) tokenized = multiDotRegex4.replaceAllIn(tokenized, "DOTMULTI.") tokenized = multiDotRegex5.replaceAllIn(tokenized, ".") // Escape special characters. if (escapeSpecialCharacters) { tokenized = preEscapeRegex1.replaceAllIn(tokenized, "&amp;") tokenized = preEscapeRegex2.replaceAllIn(tokenized, "&#124;") tokenized = preEscapeRegex3.replaceAllIn(tokenized, "&lt;") tokenized = preEscapeRegex4.replaceAllIn(tokenized, "&gt;") tokenized = preEscapeRegex5.replaceAllIn(tokenized, "&apos;") tokenized = preEscapeRegex6.replaceAllIn(tokenized, "&quot;") tokenized = preEscapeRegex7.replaceAllIn(tokenized, "&#91;") tokenized = preEscapeRegex8.replaceAllIn(tokenized, "&#93;") tokenized = escapeRegex1.replaceAllIn(tokenized, "&amp;") tokenized = escapeRegex2.replaceAllIn(tokenized, "&#124;") tokenized = escapeRegex3.replaceAllIn(tokenized, "&lt;") tokenized = escapeRegex4.replaceAllIn(tokenized, "&gt;") tokenized = escapeRegex5.replaceAllIn(tokenized, "&apos;") tokenized = escapeRegex6.replaceAllIn(tokenized, "&quot;") tokenized = escapeRegex7.replaceAllIn(tokenized, "&#91;") tokenized = escapeRegex8.replaceAllIn(tokenized, "&#93;") } tokenized } override def toString: String = "t:moses" } object MosesTokenizer { case class NonBreakingPrefixes(prefixes: Set[String] = Set.empty, numericPrefixes: Set[String] = Set.empty) private[data] val defaultNonBreakingPrefixes = Map( Catalan -> NonBreakingPrefixes( prefixes = Set( "Dr", "Dra", "pàg", "p", "c", "av", "Sr", "Sra", "adm", "esq", "Prof", "S.A", "S.L", "p.e", "ptes", "Sta", "St", "pl", "màx", "cast", "dir", "nre", "fra", "admdora", "Emm", "Excma", "espf", "dc", "admdor", "tel", "angl", "aprox", "ca", "dept", "dj", "dl", "dt", "ds", "dg", "dv", "ed", "entl", "al", "i.e", "maj", "smin", "n", "núm", "pta", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")), Chinese -> NonBreakingPrefixes( prefixes = Set( "A", "Ā", "B", "C", "Č", "D", "E", "Ē", "F", "G", "Ģ", "H", "I", "Ī", "J", "K", "Ķ", "L", "Ļ", "M", "N", "Ņ", "O", "P", "Q", "R", "S", "Š", "T", "U", "Ū", "V", "W", "X", "Y", "Z", "Ž"), numericPrefixes = Set("No", "Nr")), Czech -> NonBreakingPrefixes( prefixes = Set( "Bc", "BcA", "Ing", "Ing.arch", "MUDr", "MVDr", "MgA", "Mgr", "JUDr", "PhDr", "RNDr", "PharmDr", "ThLic", "ThDr", "Ph.D", "Th.D", "prof", "doc", "CSc", "DrSc", "dr. h. c", "PaedDr", "Dr", "PhMr", "DiS", "abt", "ad", "a.i", "aj", "angl", "anon", "apod", "atd", "atp", "aut", "bd", "biogr", "b.m", "b.p", "b.r", "cca", "cit", "cizojaz", "c.k", "col", "čes", "čín", "čj", "ed", "facs", "fasc", "fol", "fot", "franc", "h.c", "hist", "hl", "hrsg", "ibid", "il", "ind", "inv.č", "jap", "jhdt", "jv", "koed", "kol", "korej", "kl", "krit", "lat", "lit", "m.a", "maď", "mj", "mp", "násl", "např", "nepubl", "něm", "no", "nr", "n.s", "okr", "odd", "odp", "obr", "opr", "orig", "phil", "pl", "pokrač", "pol", "port", "pozn", "př.kr", "př.n.l", "přel", "přeprac", "příl", "pseud", "pt", "red", "repr", "resp", "revid", "rkp", "roč", "roz", "rozš", "samost", "sect", "sest", "seš", "sign", "sl", "srv", "stol", "sv", "šk", "šk.ro", "špan", "tab", "t.č", "tis", "tj", "tř", "tzv", "univ", "uspoř", "vol", "vl.jm", "vs", "vyd", "vyobr", "zal", "zejm", "zkr", "zprac", "zvl", "n.p", "např", "než", "MUDr", "abl", "absol", "adj", "adv", "ak", "ak. sl", "akt", "alch", "amer", "anat", "angl", "anglosas", "arab", "arch", "archit", "arg", "astr", "astrol", "att", "bás", "belg", "bibl", "biol", "boh", "bot", "bulh", "círk", "csl", "č", "čas", "čes", "dat", "děj", "dep", "dět", "dial", "dór", "dopr", "dosl", "ekon", "epic", "etnonym", "eufem", "f", "fam", "fem", "fil", "film", "form", "fot", "fr", "fut", "fyz", "gen", "geogr", "geol", "geom", "germ", "gram", "hebr", "herald", "hist", "hl", "hovor", "hud", "hut", "chcsl", "chem", "ie", "imp", "impf", "ind", "indoevr", "inf", "instr", "interj", "ión", "iron", "it", "kanad", "katalán", "klas", "kniž", "komp", "konj", " ", "konkr", "kř", "kuch", "lat", "lék", "les", "lid", "lit", "liturg", "lok", "log", "m", "mat", "meteor", "metr", "mod", "ms", "mysl", "n", "náb", "námoř", "neklas", "něm", "nesklon", "nom", "ob", "obch", "obyč", "ojed", "opt", "part", "pas", "pejor", "pers", "pf", "pl", "plpf", " ", "práv", "prep", "předl", "přivl", "r", "rcsl", "refl", "reg", "rkp", "ř", "řec", "s", "samohl", "sg", "sl", "souhl", "spec", "srov", "stfr", "střv", "stsl", "subj", "subst", "superl", "sv", "sz", "táz", "tech", "telev", "teol", "trans", "typogr", "var", "vedl", "verb", "vl. jm", "voj", "vok", "vůb", "vulg", "výtv", "vztaž", "zahr", "zájm", "zast", "zejm", " ", "zeměd", "zkr", "zř", "mj", "dl", "atp", "sport", "Mgr", "horn", "MVDr", "JUDr", "RSDr", "Bc", "PhDr", "ThDr", "Ing", "aj", "apod", "PharmDr", "pomn", "ev", "slang", "nprap", "odp", "dop", "pol", "st", "stol", "p. n. l", "před n. l", "n. l", "př. Kr", "po Kr", "př. n. l", "odd", "RNDr", "tzv", "atd", "tzn", "resp", "tj", "p", "br", "č. j", "čj", "č. p", "čp", "a. s", "s. r. o", "spol. s r. o", "p. o", "s. p", "v. o. s", "k. s", "o. p. s", "o. s", "v. r", "v z", "ml", "vč", "kr", "mld", "hod", "popř", "ap", "event", "rus", "slov", "rum", "švýc", "P. T", "zvl", "hor", "dol", "S.O.S")), Dutch -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", // List of titles. These are often followed by upper-case names, but do not indicate sentence breaks. "bacc", "bc", "bgen", "c.i", "dhr", "dr", "dr.h.c", "drs", "drs", "ds", "eint", "fa", "Fa", "fam", "gen", "genm", "ing", "ir", "jhr", "jkvr", "jr", "kand", "kol", "lgen", "lkol", "Lt", "maj", "Mej", "mevr", "Mme", "mr", "mr", "Mw", "o.b.s", "plv", "prof", "ritm", "tint", "Vz", "Z.D", "Z.D.H", "Z.E", "Z.Em", "Z.H", "Z.K.H", "Z.K.M", "Z.M", "z.v", // Miscellaneous symbols. "a.g.v", "bijv", "bijz", "bv", "d.w.z", "e.c", "e.g", "e.k", "ev", "i.p.v", "i.s.m", "i.t.t", "i.v.m", "m.a.w", "m.b.t", "m.b.v", "m.h.o", "m.i", "m.i.v", "v.w.t", "Nrs", "nrs"), numericPrefixes = Set("Nr", "nr")), English -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", // List of titles. These are often followed by upper-case names, but do not indicate sentence breaks. "Adj", "Adm", "Adv", "Asst", "Bart", "Bldg", "Brig", "Bros", "Capt", "Cmdr", "Col", "Comdr", "Con", "Corp", "Cpl", "DR", "Dr", "Drs", "Ens", "Gen", "Gov", "Hon", "Hr", "Hosp", "Insp", "Lt", "MM", "MR", "MRS", "MS", "Maj", "Messrs", "Mlle", "Mme", "Mr", "Mrs", "Ms", "Msgr", "Op", "Ord", "Pfc", "Ph", "Prof", "Pvt", "Rep", "Reps", "Res", "Rev", "Rt", "Sen", "Sens", "Sfc", "Sgt", "Sr", "St", "Supt", "Surg", // Miscellaneous symbols - we add period-ending items that never indicate breaks ("p.m." does not fall into this // category - it sometimes ends a sentence). "v", "vs", "i.e", "rev", "e.g", "Nos", "Nr", // Month abbreviations (note that "May" is also a full word and is thus not included here). "Jan", "Feb", "Mar", "Apr", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), numericPrefixes = Set( // Numbers only. These should only induce breaks when followed by a numeric sequence. "No", "Art", "pp")), Finnish -> NonBreakingPrefixes( // This list is compiled from the omorfi (http://code.google.com/p/omorfi) database by Tommi A Pirinen. prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Å", "Ä", "Ö", // List of titles. These are often followed by upper-case names, but do not indicate sentence breaks. "alik", "alil", "amir", "apul", "apul.prof", "arkkit", "ass", "assist", "dipl", "dipl.arkkit", "dipl.ekon", "dipl.ins", "dipl.kielenk", "dipl.kirjeenv", "dipl.kosm", "dipl.urk", "dos", "erikoiseläinl", "erikoishammasl", "erikoisl", "erikoist", "ev.luutn", "evp", "fil", "ft", "hallinton", "hallintot", "hammaslääket", "jatk", "jääk", "kansaned", "kapt", "kapt.luutn", "kenr", "kenr.luutn", "kenr.maj", "kers", "kirjeenv", "kom", "kom.kapt", "komm", "konst", "korpr", "luutn", "maist", "maj", "Mr", "Mrs", "Ms", "M.Sc", "neuv", "nimim", "Ph.D", "prof", "puh.joht", "pääll", "res", "san", "siht", "suom", "sähköp", "säv", "toht", "toim", "toim.apul", "toim.joht", "toim.siht", "tuom", "ups", "vänr", "vääp", "ye.ups", "ylik", "ylil", "ylim", "ylimatr", "yliop", "yliopp", "ylip", "yliv", // Miscellaneous symbols - odd period-ending items that never indicate sentence breaks ("p.m." does not fall // into this category - it sometimes ends a sentence). "e.g", "ent", "esim", "huom", "i.e", "ilm", "l", "mm", "myöh", "nk", "nyk", "par", "po", "t", "v")), French -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. No french words end in // single lower-case letters, and so we throw those in too. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", // Period-final abbreviation list for French. "A.C.N", "A.M", "art", "ann", "apr", "av", "auj", "lib", "B.P", "boul", "ca", "c.-à-d", "cf", "ch.-l", "chap", "contr", "C.P.I", "C.Q.F.D", "C.N", "C.N.S", "C.S", "dir", "éd", "e.g", "env", "al", "etc", "E.V", "ex", "fasc", "fém", "fig", "fr", "hab", "ibid", "id", "i.e", "inf", "LL.AA", "LL.AA.II", "LL.AA.RR", "LL.AA.SS", "L.D", "LL.EE", "LL.MM", "LL.MM.II.RR", "loc.cit", "masc", "MM", "ms", "N.B", "N.D.A", "N.D.L.R", "N.D.T", "n/réf", "NN.SS", "N.S", "N.D", "N.P.A.I", "p.c.c", "pl", "pp", "p.ex", "p.j", "P.S", "R.A.S", "R.-V", "R.P", "R.I.P", "SS", "S.S", "S.A", "S.A.I", "S.A.R", "S.A.S", "S.E", "sec", "sect", "sing", "S.M", "S.M.I.R", "sq", "sqq", "suiv", "sup", "suppl", "tél", "T.S.V.P", "vb", "vol", "vs", "X.O", "Z.I")), German -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. No german words end in // single lower-case letters, and so we throw those in too. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", // Roman Numerals. A dot after one of these is not a sentence break in German. "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x", "xi", "xii", "xiii", "xiv", "xv", "xvi", "xvii", "xviii", "xix", "xx", // Titles and honorifics. "Adj", "Adm", "Adv", "Asst", "Bart", "Bldg", "Brig", "Bros", "Capt", "Cmdr", "Col", "Comdr", "Con", "Corp", "Cpl", "DR", "Dr", "Ens", "Gen", "Gov", "Hon", "Hosp", "Insp", "Lt", "MM", "MR", "MRS", "MS", "Maj", "Messrs", "Mlle", "Mme", "Mr", "Mrs", "Ms", "Msgr", "Op", "Ord", "Pfc", "Ph", "Prof", "Pvt", "Rep", "Reps", "Res", "Rev", "Rt", "Sen", "Sens", "Sfc", "Sgt", "Sr", "St", "Supt", "Surg", // Miscellaneous symbols. "Mio", "Mrd", "bzw", "v", "vs", "usw", "d.h", "z.B", "u.a", "etc", "Mrd", "MwSt", "ggf", "d.J", "D.h", "m.E", "vgl", "I.F", "z.T", "sogen", "ff", "u.E", "g.U", "g.g.A", "c.-à-d", "Buchst", "u.s.w", "sog", "u.ä", "Std", "evtl", "Zt", "Chr", "u.U", "o.ä", "Ltd", "b.A", "z.Zt", "spp", "sen", "SA", "k.o", "jun", "i.H.v", "dgl", "dergl", "Co", "zzt", "usf", "s.p.a", "Dkr", "Corp", "bzgl", "BSE", "Nos", "Nr", "ca", "Ca", // Ordinals are denoted with "." in German - "1." = "1st" in English. "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99"), numericPrefixes = Set( // Numbers only. These should only induce breaks when followed by a numeric sequence. "No", "Art", "pp")), Greek -> NonBreakingPrefixes( prefixes = Set( // Single letters in upper-case are usually abbreviations of names. "Α", "Β", "Γ", "Δ", "Ε", "Ζ", "Η", "Θ", "Ι", "Κ", "Λ", "Μ", "Ν", "Ξ", "Ο", "Π", "Ρ", "Σ", "Τ", "Υ", "Φ", "Χ", "Ψ", "Ω", // Includes abbreviations for the Greek language compiled from various sources (Greek grammar books, Greek // language related web content). "Άθαν", "Έγχρ", "Έκθ", "Έσδ", "Έφ", "Όμ", "Α΄Έσδρ", "Α΄Έσδ", "Α΄Βασ", "Α΄Θεσ", "Α΄Ιω", "Α΄Κορινθ", "Α΄Κορ", "Α΄Μακκ", "Α΄Μακ", "Α΄Πέτρ", "Α΄Πέτ", "Α΄Παραλ", "Α΄Πε", "Α΄Σαμ", "Α΄Τιμ", "Α΄Χρον", "Α΄Χρ", "Α.Β.Α", "Α.Β", "Α.Ε", "Α.Κ.Τ.Ο", "Αέθλ", "Αέτ", "Αίλ.Δ", "Αίλ.Τακτ", "Αίσ", "Αββακ", "Αβυδ", "Αβ", "Αγάκλ", "Αγάπ", "Αγάπ.Αμαρτ.Σ", "Αγάπ.Γεωπ", "Αγαθάγγ", "Αγαθήμ", "Αγαθιν", "Αγαθοκλ", "Αγαθρχ", "Αγαθ", "Αγαθ.Ιστ", "Αγαλλ", "Αγαπητ", "Αγγ", "Αγησ", "Αγλ", "Αγορ.Κ", "Αγρο.Κωδ", "Αγρ.Εξ", "Αγρ.Κ", "Αγ.Γρ", "Αδριαν", "Αδρ", "Αετ", "Αθάν", "Αθήν", "Αθήν.Επιγρ", "Αθήν.Επιτ", "Αθήν.Ιατρ", "Αθήν.Μηχ", "Αθανάσ", "Αθαν", "Αθηνί", "Αθηναγ", "Αθηνόδ", "Αθ", "Αθ.Αρχ", "Αιλ", "Αιλ.Επιστ", "Αιλ.ΖΙ", "Αιλ.ΠΙ", "Αιλ.απ", "Αιμιλ", "Αιν.Γαζ", "Αιν.Τακτ", "Αισχίν", "Αισχίν.Επιστ", "Αισχ", "Αισχ.Αγαμ", "Αισχ.Αγ", "Αισχ.Αλ", "Αισχ.Ελεγ", "Αισχ.Επτ.Θ", "Αισχ.Ευμ", "Αισχ.Ικέτ", "Αισχ.Ικ", "Αισχ.Περσ", "Αισχ.Προμ.Δεσμ", "Αισχ.Πρ", "Αισχ.Χοηφ", "Αισχ.Χο", "Αισχ.απ", "ΑιτΕ", "Αιτ", "Αλκ", "Αλχιας", "Αμ.Π.Ο", "Αμβ", "Αμμών", "Αμ.", "Αν.Πειθ.Συμβ.Δικ", "Ανακρ", "Ανακ", "Αναμν.Τόμ", "Αναπλ", "Ανδ", "Ανθλγος", "Ανθστης", "Αντισθ", "Ανχης", "Αν", "Αποκ", "Απρ", "Απόδ", "Απόφ", "Απόφ.Νομ", "Απ", "Απ.Δαπ", "Απ.Διατ", "Απ.Επιστ", "Αριθ", "Αριστοτ", "Αριστοφ", "Αριστοφ.Όρν", "Αριστοφ.Αχ", "Αριστοφ.Βάτρ", "Αριστοφ.Ειρ", "Αριστοφ.Εκκλ", "Αριστοφ.Θεσμ", "Αριστοφ.Ιππ", "Αριστοφ.Λυσ", "Αριστοφ.Νεφ", "Αριστοφ.Πλ", "Αριστοφ.Σφ", "Αριστ", "Αριστ.Αθ.Πολ", "Αριστ.Αισθ", "Αριστ.Αν.Πρ", "Αριστ.Ζ.Ι", "Αριστ.Ηθ.Ευδ", "Αριστ.Ηθ.Νικ", "Αριστ.Κατ", "Αριστ.Μετ", "Αριστ.Πολ", "Αριστ.Φυσιογν", "Αριστ.Φυσ", "Αριστ.Ψυχ", "Αριστ.Ρητ", "Αρμεν", "Αρμ", "Αρχ.Εκ.Καν.Δ", "Αρχ.Ευβ.Μελ", "Αρχ.Ιδ.Δ", "Αρχ.Νομ", "Αρχ.Ν", "Αρχ.Π.Ε", "Αρ", "Αρ.Φορ.Μητρ", "Ασμ", "Ασμ.ασμ", "Αστ.Δ", "Αστ.Χρον", "Ασ", "Ατομ.Γνωμ", "Αυγ", "Αφρ", "Αχ.Νομ", "Α", "Α.Εγχ.Π", "Α.Κ.΄Υδρας", "Β΄Έσδρ", "Β΄Έσδ", "Β΄Βασ", "Β΄Θεσ", "Β΄Ιω", "Β΄Κορινθ", "Β΄Κορ", "Β΄Μακκ", "Β΄Μακ", "Β΄Πέτρ", "Β΄Πέτ", "Β΄Πέ", "Β΄Παραλ", "Β΄Σαμ", "Β΄Τιμ", "Β΄Χρον", "Β΄Χρ", "Β.Ι.Π.Ε", "Β.Κ.Τ", "Β.Κ.Ψ.Β", "Β.Μ", "Β.Ο.Α.Κ", "Β.Ο.Α", "Β.Ο.Δ", "Βίβλ", "Βαρ", "ΒεΘ", "Βι.Περ", "Βιπερ", "Βιργ", "Βλγ", "Βούλ", "Βρ", "Γ΄Βασ", "Γ΄Μακκ", "ΓΕΝμλ", "Γέν", "Γαλ", "Γεν", "Γλ", "Γν.Ν.Σ.Κρ", "Γνωμ", "Γν", "Γράμμ", "Γρηγ.Ναζ", "Γρηγ.Νύσ", "Γ Νοσ", "Γ' Ογκολ", "Γ.Ν", "Δ΄Βασ", "Δ.Β", "Δ.Δίκη", "Δ.Δίκ", "Δ.Ε.Σ", "Δ.Ε.Φ.Α", "Δ.Ε.Φ", "Δ.Εργ.Ν", "Δαμ", "Δαμ.μνημ.έργ", "Δαν", "Δασ.Κ", "Δεκ", "Δελτ.Δικ.Ε.Τ.Ε", "Δελτ.Νομ", "Δελτ.Συνδ.Α.Ε", "Δερμ", "Δευτ", "Δεύτ", "Δημοσθ", "Δημόκρ", "Δι.Δικ", "Διάτ", "Διαιτ.Απ", "Διαιτ", "Διαρκ.Στρατ", "Δικ", "Διοίκ.Πρωτ", "ΔιοικΔνη", "Διοικ.Εφ", "Διον.Αρ", "Διόρθ.Λαθ", "Δ.κ.Π", "Δνη", "Δν", "Δογμ.Όρος", "Δρ", "Δ.τ.Α", "Δτ", "ΔωδΝομ", "Δ.Περ", "Δ.Στρ", "ΕΔΠολ", "ΕΕυρΚ", "ΕΙΣ", "ΕΝαυτΔ", "ΕΣΑμΕΑ", "ΕΣΘ", "ΕΣυγκΔ", "ΕΤρΑξΧρΔ", "Ε.Φ.Ε.Τ", "Ε.Φ.Ι", "Ε.Φ.Ο.Επ.Α", "Εβδ", "Εβρ", "Εγκύκλ.Επιστ", "Εγκ", "Εε.Αιγ", "Εθν.Κ.Τ", "Εθν", "Ειδ.Δικ.Αγ.Κακ", "Εικ", "Ειρ.Αθ", "Ειρην.Αθ", "Ειρην", "Έλεγχ", "Ειρ", "Εισ.Α.Π", "Εισ.Ε", "Εισ.Ν.Α.Κ", "Εισ.Ν.Κ.Πολ.Δ", "Εισ.Πρωτ", "Εισηγ.Έκθ", "Εισ", "Εκκλ", "Εκκ", "Εκ", "Ελλ.Δνη", "Εν.Ε", "Εξ", "Επ.Αν", "Επ.Εργ.Δ", "Επ.Εφ", "Επ.Κυπ.Δ", "Επ.Μεσ.Αρχ", "Επ.Νομ", "Επίκτ", "Επίκ", "Επι.Δ.Ε", "Επιθ.Ναυτ.Δικ", "Επικ", "Επισκ.Ε.Δ", "Επισκ.Εμπ.Δικ", "Επιστ.Επετ.Αρμ", "Επιστ.Επετ", "Επιστ.Ιερ", "Επιτρ.Προστ.Συνδ.Στελ", "Επιφάν", "Επτ.Εφ", "Επ.Ιρ", "Επ.Ι", "Εργ.Ασφ.Νομ", "Ερμ.Α.Κ", "Ερμη.Σ", "Εσθ", "Εσπερ", "Ετρ.Δ", "Ευκλ", "Ευρ.Δ.Δ.Α", "Ευρ.Σ.Δ.Α", "Ευρ.ΣτΕ", "Ευρατόμ", "Ευρ.Άλκ", "Ευρ.Ανδρομ", "Ευρ.Βάκχ", "Ευρ.Εκ", "Ευρ.Ελ", "Ευρ.Ηλ", "Ευρ.Ηρακ", "Ευρ.Ηρ", "Ευρ.Ηρ.Μαιν", "Ευρ.Ικέτ", "Ευρ.Ιππόλ", "Ευρ.Ιφ.Α", "Ευρ.Ιφ.Τ", "Ευρ.Ι.Τ", "Ευρ.Κύκλ", "Ευρ.Μήδ", "Ευρ.Ορ", "Ευρ.Ρήσ", "Ευρ.Τρωάδ", "Ευρ.Φοίν", "Εφ.Αθ", "Εφ.Εν", "Εφ.Επ", "Εφ.Θρ", "Εφ.Θ", "Εφ.Ι", "Εφ.Κερ", "Εφ.Κρ", "Εφ.Λ", "Εφ.Ν", "Εφ.Πατ", "Εφ.Πειρ", "Εφαρμ.Δ.Δ", "Εφαρμ", "Εφεσ", "Εφημ", "Εφ", "Ζαχ", "Ζιγ", "Ζυ", "Ζχ", "ΗΕ.Δ", "Ημερ", "Ηράκλ", "Ηροδ", "Ησίοδ", "Ησ", "Η.Ε.Γ", "ΘΗΣ", "ΘΡ", "Θαλ", "Θεοδ", "Θεοφ", "Θεσ", "Θεόδ.Μοψ", "Θεόκρ", "Θεόφιλ", "Θουκ", "Θρ", "Θρ.Ε", "Θρ.Ιερ", "Θρ.Ιρ", "Ιακ", "Ιαν", "Ιβ", "Ιδθ", "Ιδ", "Ιεζ", "Ιερ", "Ιζ", "Ιησ", "Ιησ.Ν", "Ικ", "Ιλ", "Ιν", "Ιουδ", "Ιουστ", "Ιούδα", "Ιούλ", "Ιούν", "Ιπποκρ", "Ιππόλ", "Ιρ", "Ισίδ.Πηλ", "Ισοκρ", "Ισ.Ν", "Ιωβ", "Ιωλ", "Ιων", "Ιω", "ΚΟΣ", "ΚΟ.ΜΕ.ΚΟΝ", "ΚΠοινΔ", "ΚΠολΔ", "ΚαΒ", "Καλ", "Καλ.Τέχν", "ΚανΒ", "Καν.Διαδ", "Κατάργ", "Κλ", "ΚοινΔ", "Κολσ", "Κολ", "Κον", "Κορ", "Κος", "ΚριτΕπιθ", "ΚριτΕ", "Κριτ", "Κρ", "ΚτΒ", "ΚτΕ", "ΚτΠ", "Κυβ", "Κυπρ", "Κύριλ.Αλεξ", "Κύριλ.Ιερ", "Λεβ", "Λεξ.Σουίδα", "Λευϊτ", "Λευ", "Λκ", "Λογ", "ΛουκΑμ", "Λουκιαν", "Λουκ.Έρωτ", "Λουκ.Ενάλ.Διάλ", "Λουκ.Ερμ", "Λουκ.Εταιρ.Διάλ", "Λουκ.Ε.Δ", "Λουκ.Θε.Δ", "Λουκ.Ικ.", "Λουκ.Ιππ", "Λουκ.Λεξιφ", "Λουκ.Μεν", "Λουκ.Μισθ.Συν", "Λουκ.Ορχ", "Λουκ.Περ", "Λουκ.Συρ", "Λουκ.Τοξ", "Λουκ.Τυρ", "Λουκ.Φιλοψ", "Λουκ.Φιλ", "Λουκ.Χάρ", "Λουκ.", "Λουκ.Αλ", "Λοχ", "Λυδ", "Λυκ", "Λυσ", "Λωζ", "Λ1", "Λ2", "ΜΟΕφ", "Μάρκ", "Μέν", "Μαλ", "Ματθ", "Μα", "Μιχ", "Μκ", "Μλ", "Μμ", "Μον.Δ.Π", "Μον.Πρωτ", "Μον", "Μρ", "Μτ", "Μχ", "Μ.Βασ", "Μ.Πλ", "ΝΑ", "Ναυτ.Χρον", "Να", "Νδικ", "Νεεμ", "Νε", "Νικ", "ΝκΦ", "Νμ", "ΝοΒ", "Νομ.Δελτ.Τρ.Ελ", "Νομ.Δελτ", "Νομ.Σ.Κ", "Νομ.Χρ", "Νομ", "Νομ.Διεύθ", "Νοσ", "Ντ", "Νόσων", "Ν1", "Ν2", "Ν3", "Ν4", "Νtot", "Ξενοφ", "Ξεν", "Ξεν.Ανάβ", "Ξεν.Απολ", "Ξεν.Απομν", "Ξεν.Απομ", "Ξεν.Ελλ", "Ξεν.Ιέρ", "Ξεν.Ιππαρχ", "Ξεν.Ιππ", "Ξεν.Κυρ.Αν", "Ξεν.Κύρ.Παιδ", "Ξεν.Κ.Π", "Ξεν.Λακ.Πολ", "Ξεν.Οικ", "Ξεν.Προσ", "Ξεν.Συμπόσ", "Ξεν.Συμπ", "Ο΄", "Οβδ", "Οβ", "ΟικΕ", "Οικ", "Οικ.Πατρ", "Οικ.Σύν.Βατ", "Ολομ", "Ολ", "Ολ.Α.Π", "Ομ.Ιλ", "Ομ.Οδ", "ΟπΤοιχ", "Οράτ", "Ορθ", "ΠΡΟ.ΠΟ", "Πίνδ", "Πίνδ.Ι", "Πίνδ.Νεμ", "Πίνδ.Ν", "Πίνδ.Ολ", "Πίνδ.Παθ", "Πίνδ.Πυθ", "Πίνδ.Π", "ΠαγΝμλγ", "Παν", "Παρμ", "Παροιμ", "Παρ", "Παυσ", "Πειθ.Συμβ", "ΠειρΝ", "Πελ", "ΠεντΣτρ", "Πεντ", "Πεντ.Εφ", "ΠερΔικ", "Περ.Γεν.Νοσ", "Πετ", "Πλάτ", "Πλάτ.Αλκ", "Πλάτ.Αντ", "Πλάτ.Αξίοχ", "Πλάτ.Απόλ", "Πλάτ.Γοργ", "Πλάτ.Ευθ", "Πλάτ.Θεαίτ", "Πλάτ.Κρατ", "Πλάτ.Κριτ", "Πλάτ.Λύσ", "Πλάτ.Μεν", "Πλάτ.Νόμ", "Πλάτ.Πολιτ", "Πλάτ.Πολ", "Πλάτ.Πρωτ", "Πλάτ.Σοφ.", "Πλάτ.Συμπ", "Πλάτ.Τίμ", "Πλάτ.Φαίδρ", "Πλάτ.Φιλ", "Πλημ", "Πλούτ", "Πλούτ.Άρατ", "Πλούτ.Αιμ", "Πλούτ.Αλέξ", "Πλούτ.Αλκ", "Πλούτ.Αντ", "Πλούτ.Αρτ", "Πλούτ.Ηθ", "Πλούτ.Θεμ", "Πλούτ.Κάμ", "Πλούτ.Καίσ", "Πλούτ.Κικ", "Πλούτ.Κράσ", "Πλούτ.Κ", "Πλούτ.Λυκ", "Πλούτ.Μάρκ", "Πλούτ.Μάρ", "Πλούτ.Περ", "Πλούτ.Ρωμ", "Πλούτ.Σύλλ", "Πλούτ.Φλαμ", "Πλ", "Ποιν.Δικ", "Ποιν.Δ", "Ποιν.Ν", "Ποιν.Χρον", "Ποιν.Χρ", "Πολ.Δ", "Πολ.Πρωτ", "Πολ", "Πολ.Μηχ", "Πολ.Μ", "Πρακτ.Αναθ", "Πρακτ.Ολ", "Πραξ", "Πρμ", "Πρξ", "Πρωτ", "Πρ", "Πρ.Αν", "Πρ.Λογ", "Πταισμ", "Πυρ.Καλ", "Πόλη", "Π.Δ", "Π.Δ.Άσμ", "ΡΜ.Ε", "Ρθ", "Ρμ", "Ρωμ", "ΣΠλημ", "Σαπφ", "Σειρ", "Σολ", "Σοφ", "Σοφ.Αντιγ", "Σοφ.Αντ", "Σοφ.Αποσ", "Σοφ.Απ", "Σοφ.Ηλέκ", "Σοφ.Ηλ", "Σοφ.Οιδ.Κολ", "Σοφ.Οιδ.Τύρ", "Σοφ.Ο.Τ", "Σοφ.Σειρ", "Σοφ.Σολ", "Σοφ.Τραχ", "Σοφ.Φιλοκτ", "Σρ", "Σ.τ.Ε", "Σ.τ.Π", "Στρ.Π.Κ", "Στ.Ευρ", "Συζήτ", "Συλλ.Νομολ", "Συλ.Νομ", "ΣυμβΕπιθ", "Συμπ.Ν", "Συνθ.Αμ", "Συνθ.Ε.Ε", "Συνθ.Ε.Κ", "Συνθ.Ν", "Σφν", "Σφ", "Σφ.Σλ", "Σχ.Πολ.Δ", "Σχ.Συντ.Ε", "Σωσ", "Σύντ", "Σ.Πληρ", "ΤΘ", "ΤΣ.Δ", "Τίτ", "Τβ", "Τελ.Ενημ", "Τελ.Κ", "Τερτυλ", "Τιμ", "Τοπ.Α", "Τρ.Ο", "Τριμ", "Τριμ.Πλ", "Τρ.Πλημ", "Τρ.Π.Δ", "Τ.τ.Ε", "Ττ", "Τωβ", "Υγ", "Υπερ", "Υπ", "Υ.Γ", "Φιλήμ", "Φιλιπ", "Φιλ", "Φλμ", "Φλ", "Φορ.Β", "Φορ.Δ.Ε", "Φορ.Δνη", "Φορ.Δ", "Φορ.Επ", "Φώτ", "Χρ.Ι.Δ", "Χρ.Ιδ.Δ", "Χρ.Ο", "Χρυσ", "Ψήφ", "Ψαλμ", "Ψαλ", "Ψλ", "Ωριγ", "Ωσ", "Ω.Ρ.Λ", "άγν", "άγν.ετυμολ", "άγ", "άκλ", "άνθρ", "άπ", "άρθρ", "άρν", "άρ", "άτ", "άψ", "ά", "έκδ", "έκφρ", "έμψ", "ένθ.αν", "έτ", "έ.α", "ίδ", "αβεστ", "αβησσ", "αγγλ", "αγγ", "αδημ", "αεροναυτ", "αερον", "αεροπ", "αθλητ", "αθλ", "αθροιστ", "αιγυπτ", "αιγ", "αιτιολ", "αιτ", "αι", "ακαδ", "ακκαδ", "αλβ", "αλλ", "αλφαβητ", "αμα", "αμερικ", "αμερ", "αμετάβ", "αμτβ", "αμφιβ", "αμφισβ", "αμφ", "αμ", "ανάλ", "ανάπτ", "ανάτ", "αναβ", "αναδαν", "αναδιπλασ", "αναδιπλ", "αναδρ", "αναλ", "αναν", "ανασυλλ", "ανατολ", "ανατομ", "ανατυπ", "ανατ", "αναφορ", "αναφ", "ανα.ε", "ανδρων", "ανθρωπολ", "ανθρωπ", "ανθ", "ανομ", "αντίτ", "αντδ", "αντιγρ", "αντιθ", "αντικ", "αντιμετάθ", "αντων", "αντ", "ανωτ", "ανόργ", "ανών", "αορ", "απαρέμφ", "απαρφ", "απαρχ", "απαρ", "απλολ", "απλοπ", "αποβ", "αποηχηροπ", "αποθ", "αποκρυφ", "αποφ", "απρμφ", "απρφ", "απρόσ", "απόδ", "απόλ", "απόσπ", "απόφ", "αραβοτουρκ", "αραβ", "αραμ", "αρβαν", "αργκ", "αριθμτ", "αριθμ", "αριθ", "αρκτικόλ", "αρκ", "αρμεν", "αρμ", "αρνητ", "αρσ", "αρχαιολ", "αρχιτεκτ", "αρχιτ", "αρχκ", "αρχ", "αρωμουν", "αρωμ", "αρ", "αρ.μετρ", "αρ.φ", "ασσυρ", "αστρολ", "αστροναυτ", "αστρον", "αττ", "αυστραλ", "αυτοπ", "αυτ", "αφγαν", "αφηρ", "αφομ", "αφρικ", "αχώρ", "αόρ", "α.α", "α/α", "α0", "βαθμ", "βαθ", "βαπτ", "βασκ", "βεβαιωτ", "βεβ", "βεδ", "βενετ", "βεν", "βερβερ", "βιβλγρ", "βιολ", "βιομ", "βιοχημ", "βιοχ", "βλάχ", "βλ", "βλ.λ", "βοταν", "βοτ", "βουλγαρ", "βουλγ", "βούλ", "βραζιλ", "βρετον", "βόρ", "γαλλ", "γενικότ", "γενοβ", "γεν", "γερμαν", "γερμ", "γεωγρ", "γεωλ", "γεωμετρ", "γεωμ", "γεωπ", "γεωργ", "γλυπτ", "γλωσσολ", "γλωσσ", "γλ", "γνμδ", "γνμ", "γνωμ", "γοτθ", "γραμμ", "γραμ", "γρμ", "γρ", "γυμν", "δίδες", "δίκ", "δίφθ", "δαν", "δεικτ", "δεκατ", "δηλ", "δημογρ", "δημοτ", "δημώδ", "δημ", "διάγρ", "διάκρ", "διάλεξ", "διάλ", "διάσπ", "διαλεκτ", "διατρ", "διαφ", "διαχ", "διδα", "διεθν", "διεθ", "δικον", "διστ", "δισύλλ", "δισ", "διφθογγοπ", "δογμ", "δολ", "δοτ", "δρμ", "δρχ", "δρ(α)", "δωρ", "δ", "εβρ", "εγκλπ", "εδ", "εθνολ", "εθν", "ειδικότ", "ειδ", "ειδ.β", "εικ", "ειρ", "εισ", "εκατοστμ", "εκατοστ", "εκατστ.2", "εκατστ.3", "εκατ", "εκδ", "εκκλησ", "εκκλ", "εκ", "ελλην", "ελλ", "ελνστ", "ελπ", "εμβ", "εμφ", "εναλλ", "ενδ", "ενεργ", "ενεστ", "ενικ", "ενν", "εν", "εξέλ", "εξακολ", "εξομάλ", "εξ", "εο", "επέκτ", "επίδρ", "επίθ", "επίρρ", "επίσ", "επαγγελμ", "επανάλ", "επανέκδ", "επιθ", "επικ", "επιμ", "επιρρ", "επιστ", "επιτατ", "επιφ", "επών", "επ", "εργ", "ερμ", "ερρινοπ", "ερωτ", "ετρουσκ", "ετυμ", "ετ", "ευφ", "ευχετ", "εφ", "εύχρ", "ε.α", "ε/υ", "ε0", "ζωγρ", "ζωολ", "ηθικ", "ηθ", "ηλεκτρολ", "ηλεκτρον", "ηλεκτρ", "ημίτ", "ημίφ", "ημιφ", "ηχηροπ", "ηχηρ", "ηχομιμ", "ηχ", "η", "θέατρ", "θεολ", "θετ", "θηλ", "θρακ", "θρησκειολ", "θρησκ", "θ", "ιαπων", "ιατρ", "ιδιωμ", "ιδ", "ινδ", "ιραν", "ισπαν", "ιστορ", "ιστ", "ισχυροπ", "ιταλ", "ιχθυολ", "ιων", "κάτ", "καθ", "κακοσ", "καν", "καρ", "κατάλ", "κατατ", "κατωτ", "κατ", "κα", "κελτ", "κεφ", "κινεζ", "κινημ", "κλητ", "κλιτ", "κλπ", "κλ", "κν", "κοινωνιολ", "κοινων", "κοπτ", "κουτσοβλαχ", "κουτσοβλ", "κπ", "κρ.γν", "κτγ", "κτην", "κτητ", "κτλ", "κτ", "κυριολ", "κυρ", "κύρ", "κ", "κ.ά", "κ.ά.π", "κ.α", "κ.εξ", "κ.επ", "κ.ε", "κ.λπ", "κ.λ.π", "κ.ού.κ", "κ.ο.κ", "κ.τ.λ", "κ.τ.τ", "κ.τ.ό", "λέξ", "λαογρ", "λαπ", "λατιν", "λατ", "λαϊκότρ", "λαϊκ", "λετ", "λιθ", "λογιστ", "λογοτ", "λογ", "λουβ", "λυδ", "λόγ", "λ", "λ.χ", "μέλλ", "μέσ", "μαθημ", "μαθ", "μαιευτ", "μαλαισ", "μαλτ", "μαμμων", "μεγεθ", "μεε", "μειωτ", "μελ", "μεξ", "μεσν", "μεσογ", "μεσοπαθ", "μεσοφ", "μετάθ", "μεταβτ", "μεταβ", "μετακ", "μεταπλ", "μεταπτωτ", "μεταρ", "μεταφορ", "μετβ", "μετεπιθ", "μετεπιρρ", "μετεωρολ", "μετεωρ", "μετον", "μετουσ", "μετοχ", "μετρ", "μετ", "μητρων", "μηχανολ", "μηχ", "μικροβιολ", "μογγολ", "μορφολ", "μουσ", "μπενελούξ", "μσνλατ", "μσν", "μτβ", "μτγν", "μτγ", "μτφρδ", "μτφρ", "μτφ", "μτχ", "μυθ", "μυκην", "μυκ", "μφ", "μ", "μ.ε", "μ.μ", "μ.π.ε", "μ.π.π", "μ0", "ναυτ", "νεοελλ", "νεολατιν", "νεολατ", "νεολ", "νεότ", "νλατ", "νομ", "νορβ", "νοσ", "νότ", "ν", "ξ.λ", "οικοδ", "οικολ", "οικον", "οικ", "ολλανδ", "ολλ", "ομηρ", "ομόρρ", "ονομ", "ον", "οπτ", "ορθογρ", "ορθ", "οριστ", "ορυκτολ", "ορυκτ", "ορ", "οσετ", "οσκ", "ουαλ", "ουγγρ", "ουδ", "ουσιαστικοπ", "ουσιαστ", "ουσ", "πίν", "παθητ", "παθολ", "παθ", "παιδ", "παλαιοντ", "παλαιότ", "παλ", "παππων", "παράγρ", "παράγ", "παράλλ", "παράλ", "παραγ", "παρακ", "παραλ", "παραπ", "παρατ", "παρβ", "παρετυμ", "παροξ", "παρων", "παρωχ", "παρ", "παρ.φρ", "πατριδων", "πατρων", "πβ", "περιθ", "περιλ", "περιφρ", "περσ", "περ", "πιθ", "πληθ", "πληροφ", "ποδ", "ποιητ", "πολιτ", "πολλαπλ", "πολ", "πορτογαλ", "πορτ", "ποσ", "πρακριτ", "πρβλ", "πρβ", "πργ", "πρκμ", "πρκ", "πρλ", "προέλ", "προβηγκ", "προελλ", "προηγ", "προθεμ", "προπαραλ", "προπαροξ", "προπερισπ", "προσαρμ", "προσηγορ", "προσταχτ", "προστ", "προσφών", "προσ", "προτακτ", "προτ.Εισ", "προφ", "προχωρ", "πρτ", "πρόθ", "πρόσθ", "πρόσ", "πρότ", "πρ", "πρ.Εφ", "πτ", "πυ", "π", "π.Χ", "π.μ", "π.χ", "ρήμ", "ρίζ", "ρηματ", "ρητορ", "ριν", "ρουμ", "ρωμ", "ρωσ", "ρ", "σανσκρ", "σαξ", "σελ", "σερβοκρ", "σερβ", "σημασιολ", "σημδ", "σημειολ", "σημερ", "σημιτ", "σημ", "σκανδ", "σκυθ", "σκωπτ", "σλαβ", "σλοβ", "σουηδ", "σουμερ", "σουπ", "σπάν", "σπανιότ", "σπ", "σσ", "στατ", "στερ", "στιγμ", "στιχ", "στρέμ", "στρατιωτ", "στρατ", "στ", "συγγ", "συγκρ", "συγκ", "συμπερ", "συμπλεκτ", "συμπλ", "συμπροφ", "συμφυρ", "συμφ", "συνήθ", "συνίζ", "συναίρ", "συναισθ", "συνδετ", "συνδ", "συνεκδ", "συνηρ", "συνθετ", "συνθ", "συνοπτ", "συντελ", "συντομογρ", "συντ", "συν", "συρ", "σχημ", "σχ", "σύγκρ", "σύμπλ", "σύμφ", "σύνδ", "σύνθ", "σύντμ", "σύντ", "σ", "σ.π", "σ/β", "τακτ", "τελ", "τετρ", "τετρ.μ", "τεχνλ", "τεχνολ", "τεχν", "τεύχ", "τηλεπικ", "τηλεόρ", "τιμ", "τιμ.τομ", "τοΣ", "τον", "τοπογρ", "τοπων", "τοπ", "τοσκ", "τουρκ", "τοχ", "τριτοπρόσ", "τροποπ", "τροπ", "τσεχ", "τσιγγ", "ττ", "τυπ", "τόμ", "τόνν", "τ", "τ.μ", "τ.χλμ", "υβρ", "υπερθ", "υπερσ", "υπερ", "υπεύθ", "υποθ", "υποκορ", "υποκ", "υποσημ", "υποτ", "υποφ", "υποχωρ", "υπόλ", "υπόχρ", "υπ", "υστλατ", "υψόμ", "υψ", "φάκ", "φαρμακολ", "φαρμ", "φιλολ", "φιλοσ", "φιλοτ", "φινλ", "φοινικ", "φράγκ", "φρανκον", "φριζ", "φρ", "φυλλ", "φυσιολ", "φυσ", "φωνηεντ", "φωνητ", "φωνολ", "φων", "φωτογρ", "φ", "φ.τ.μ", "χαμιτ", "χαρτόσ", "χαρτ", "χασμ", "χαϊδ", "χγφ", "χειλ", "χεττ", "χημ", "χιλ", "χλγρ", "χλγ", "χλμ", "χλμ.2", "χλμ.3", "χλσγρ", "χλστγρ", "χλστμ", "χλστμ.2", "χλστμ.3", "χλ", "χργρ", "χρημ", "χρον", "χρ", "χφ", "χ.ε", "χ.κ", "χ.ο", "χ.σ", "χ.τ", "χ.χ", "ψευδ", "ψυχαν", "ψυχιατρ", "ψυχολ", "ψυχ", "ωκεαν", "όμ", "όν", "όπ.παρ", "όπ.π", "ό.π", "ύψ", "1Βσ", "1Εσ", "1Θσ", "1Ιν", "1Κρ", "1Μκ", "1Πρ", "1Πτ", "1Τμ", "2Βσ", "2Εσ", "2Θσ", "2Ιν", "2Κρ", "2Μκ", "2Πρ", "2Πτ", "2Τμ", "3Βσ", "3Ιν", "3Μκ", "4Βσ")), Hungarian -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Á", "É", "Í", "Ó", "Ö", "Ő", "Ú", "Ü", "Ű", // List of titles. These are often followed by upper-case names, but do not indicate sentence breaks. "Dr", "dr", "kb", "Kb", "vö", "Vö", "pl", "Pl", "ca", "Ca", "min", "Min", "max", "Max", "ún", "Ún", "prof", "Prof", "de", "De", "du", "Du", "Szt", "St"), numericPrefixes = Set( // Month name abbreviations. "jan", "Jan", "Feb", "feb", "márc", "Márc", "ápr", "Ápr", "máj", "Máj", "jún", "Jún", "Júl", "júl", "aug", "Aug", "Szept", "szept", "okt", "Okt", "nov", "Nov", "dec", "Dec", // Other abbreviations. "tel", "Tel", "Fax", "fax")), Icelandic -> NonBreakingPrefixes( prefixes = Set( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "^", "í", "á", "ó", "æ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "ab.fn", "a.fn", "afs", "al", "alm", "alg", "andh", "ath", "aths", "atr", "ao", "au", "aukaf", "áfn", "áhrl.s", "áhrs", "ákv.gr", "ákv", "bh", "bls", "dr", "e.Kr", "et", "ef", "efn", "ennfr", "eink", "end", "e.st", "erl", "fél", "fskj", "fh", "f.hl", "físl", "fl", "fn", "fo", "forl", "frb", "frl", "frh", "frt", "fsl", "fsh", "fs", "fsk", "fst", "f.Kr", "ft", "fv", "fyrrn", "fyrrv", "germ", "gm", "gr", "hdl", "hdr", "hf", "hl", "hlsk", "hljsk", "hljv", "hljóðv", "hr", "hv", "hvk", "holl", "Hos", "höf", "hk", "hrl", "ísl", "kaf", "kap", "Khöfn", "kk", "kg", "kk", "km", "kl", "klst", "kr", "kt", "kgúrsk", "kvk", "leturbr", "lh", "lh.nt", "lh.þt", "lo", "ltr", "mlja", "mljó", "millj", "mm", "mms", "m.fl", "miðm", "mgr", "mst", "mín", "nf", "nh", "nhm", "nl", "nk", "nmgr", "no", "núv", "nt", "o.áfr", "o.m.fl", "ohf", "o.fl", "o.s.frv", "ófn", "ób", "óákv.gr", "óákv", "pfn", "PR", "pr", "Ritstj", "Rvík", "Rvk", "samb", "samhlj", "samn", "samn", "sbr", "sek", "sérn", "sf", "sfn", "sh", "sfn", "sh", "s.hl", "sk", "skv", "sl", "sn", "so", "ss.us", "s.st", "samþ", "sbr", "shlj", "sign", "skál", "st", "st.s", "stk", "sþ", "teg", "tbl", "tfn", "tl", "tvíhlj", "tvt", "till", "to", "umr", "uh", "us", "uppl", "útg", "vb", "Vf", "vh", "vkf", "Vl", "vl", "lf", "vmf", "8vo", "vsk", "vth", "þt", "þf", "þjs", "þgf", "þlt", "þolm", "þm", "þml", "þýð"), numericPrefixes = Set("no", "No", "nr", "Nr", "nR", "NR")), Irish -> NonBreakingPrefixes( prefixes = Set( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Á", "É", "Í", "Ó", "Ú", "", "Uacht", "Dr", "B.Arch", "", "m.sh", ".i", "Co", "Cf", "cf", "i.e", "r", "Chr"), numericPrefixes = Set("lch", "lgh", "uimh") ), Italian -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", // List of titles. These are often followed by upper-case names, but do not indicate sentence breaks. "Adj", "Adm", "Adv", "Amn ", "Arch ", "Asst", "Avv", "Bart", "Bcc", "Bldg", "Brig", "Bros", "C.A.P", "C.P", "Capt", "Cc", "Cmdr", "Co", "Col", "Comdr", "Con", "Corp", "Cpl", "DR", "Dott", "Dr", "Drs", "Egr", "Ens", "Gen", "Geom", "Gov", "Hon", "Hosp", "Hr", "Id", "Ing", "Insp", "Lt", "MM", "MR", "MRS", "MS", "Maj", "Messrs", "Mlle", "Mme", "Mo", "Mons", "Mr", "Mrs", "Ms", "Msgr", "N.B", "Op", "Ord", "P.S", "P.T", "Pfc", "Ph", "Prof", "Pvt", "RP", "RSVP", "Rag", "Rep", "Reps", "Res", "Rev", "Rif", "Rt", "S.A", "S.B.F", "S.P.M", "S.p.A", "S.r.l", "Sen", "Sens", "Sfc", "Sgt", "Sig", "Sigg", "Soc", "Spett", "Sr", "St", "Supt", "Surg", "V.P", "", "# other", "a.c", "acc", "all ", "banc", "c.a", "c.c.p", "c.m", "c.p", "c.s", "c.v", "corr", "dott", "e.p.c", "ecc", "es", "fatt", "gg", "int", "lett", "ogg", "on", "p.c", "p.c.c", "p.es", "p.f", "p.r", "p.v", "post", "pp", "racc", "ric", "s.n.c", "seg", "sgg", "ss", "tel", "u.s", "v.r", "v.s", // Miscellaneous symbols - we add period-ending items that never indicate breaks ("p.m." does not fall into this // category - it sometimes ends a sentence). "v", "vs", "i.e", "rev", "e.g", "Nos", "Nr"), numericPrefixes = Set( // Numbers only. These should only induce breaks when followed by a numeric sequence. "No", "Art", "pp")), Latvian -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "Ā", "B", "C", "Č", "D", "E", "Ē", "F", "G", "Ģ", "H", "I", "Ī", "J", "K", "Ķ", "L", "Ļ", "M", "N", "Ņ", "O", "P", "Q", "R", "S", "Š", "T", "U", "Ū", "V", "W", "X", "Y", "Z", "Ž", // List of titles. These are often followed by upper-case names, but do not indicate sentence breaks. "dr", "Dr", "med", "prof", "Prof", "inž", "Inž", "ist.loc", "Ist.loc", "kor.loc", "Kor.loc", "v.i", "vietn", "Vietn", // Miscellaneous symbols. "a.l", "t.p", "pārb", "Pārb", "vec", "Vec", "inv", "Inv", "sk", "Sk", "spec", "Spec", "vienk", "Vienk", "virz", "Virz", "māksl", "Māksl", "mūz", "Mūz", "akad", "Akad", "soc", "Soc", "galv", "Galv", "vad", "Vad", "sertif", "Sertif", "folkl", "Folkl", "hum", "Hum"), numericPrefixes = Set("Nr")), Lithuanian -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "Ā", "B", "C", "Č", "D", "E", "Ē", "F", "G", "Ģ", "H", "I", "Ī", "J", "K", "Ķ", "L", "Ļ", "M", "N", "Ņ", "O", "P", "Q", "R", "S", "Š", "T", "U", "Ū", "V", "W", "X", "Y", "Z", "Ž", // Other symbols. "Dz", "Dž", "Just", "m", "mėn", "d", "g", "gim", "Pr", "Pn", "Pirm", "Antr", "Treč", "Ketv", "Penkt", "Šešt", "Sekm", "Saus", "Vas", "Kov", "Bal", "Geg", "Birž", "Liep", "Rugpj", "Rugs", "Spal", "Lapkr", "Gruod", "a", "adv", "akad", "aklg", "akt", "al", "A.V", "aps", "apskr", "apyg", "aps", "apskr", "asist", "asmv", "avd", "a.k", "asm", "asm.k", "atsak", "atsisk", "sąsk", "aut", "b", "k", "b.k", "bkl", "bt", "buv", "dail", "dek", "dėst", "dir", "dirig", "doc", "drp", "dš", "egz", "eil", "ekon", "el", "etc", "ež", "faks", "fak", "gen", "gyd", "gv", "įl", "Įn", "insp", "pan", "t.t", "k.a", "kand", "kat", "kyš", "kl", "kln", "kn", "koresp", "kpt", "kr", "kt", "kun", "l", "e", "p", "l.e.p", "ltn", "m", "mst", "m.e", "m.m", "mot", "mstl", "mgr", "mgnt", "mjr", "mln", "mlrd", "mok", "mokyt", "moksl", "nkt", "ntk", "Nr", "nr", "p", "p.d", "a.d", "p.m.e", "pan", "pav", "pavad", "pirm", "pl", "plg", "plk", "pr", "Kr", "pr.Kr", "prok", "prot", "pss", "pšt", "pvz", "r", "red", "rš", "sąs", "saviv", "sav", "sekr", "sen", "sk", "skg", "skyr", "sk", "skv", "sp", "spec", "sr", "st", "str", "stud", "š", "š.m", "šnek", "tir", "tūkst", "up", "upl", "vad", "vlsč", "ved", "vet", "virš", "vyr", "vyresn", "vlsč", "vs", "Vt", "vt", "vtv", "vv", "žml", "air", "amer", "anat", "angl", "arab", "archeol", "archit", "asm", "astr", "austral", "aut", "av", "bažn", "bdv", "bibl", "biol", "bot", "brt", "brus", "buh", "chem", "col", "con", "conj", "dab", "dgs", "dial", "dipl", "dktv", "džn", "ekon", "el", "esam", "euf", "fam", "farm", "filol", "filos", "fin", "fiz", "fiziol", "flk", "fon", "fot", "geod", "geogr", "geol", "geom", "glžk", "gr", "gram", "her", "hidr", "ind", "iron", "isp", "ist", "istor", "it", "įv", "reikšm", "įv.reikšm", "jap", "juok", "jūr", "kalb", "kar", "kas", "kin", "klaus", "knyg", "kom", "komp", "kosm", "kt", "kul", "kuop", "l", "lit", "lingv", "log", "lot", "mat", "maž", "med", "medž", "men", "menk", "metal", "meteor", "min", "mit", "mok", "ms", "muz", "n", "neig", "neol", "niek", "ofic", "opt", "orig", "p", "pan", "parl", "pat", "paž", "plg", "poet", "poez", "poligr", "polit", "ppr", "pranc", "pr", "priet", "prek", "prk", "prs", "psn", "psich", "pvz", "r", "rad", "rel", "ret", "rus", "sen", "sl", "sov", "spec", "sport", "stat", "sudurt", "sutr", "suv", "š", "šach", "šiaur", "škot", "šnek", "teatr", "tech", "techn", "teig", "teis", "tekst", "tel", "teol", "v", "t.p", "t", "p", "t.t", "t.y", "vaik", "vart", "vet", "vid", "vksm", "vns", "vok", "vulg", "zool", "žr", "ž.ū", "ž", "ū", "Em.", "Gerb", "gerb", "malon", "Prof", "prof", "Dr", "dr", "habil", "med", "inž", "Inž")), Polish -> NonBreakingPrefixes( prefixes = Set( "adw", "afr", "akad", "al", "Al", "am", "amer", "arch", "art", "Art", "artyst", "astr", "austr", "bałt", "bdb", "bł", "bm", "br", "bryg", "bryt", "centr", "ces", "chem", "chiń", "chir", "c.k", "c.o", "cyg", "cyw", "cyt", "czes", "czw", "cd", "Cd", "czyt", "ćw", "ćwicz", "daw", "dcn", "dekl", "demokr", "det", "diec", "dł", "dn", "dot", "dol", "dop", "dost", "dosł", "h.c", "ds", "dst", "duszp", "dypl", "egz", "ekol", "ekon", "elektr", "em", "ew", "fab", "farm", "fot", "fr", "gat", "gastr", "geogr", "geol", "gimn", "głęb", "gm", "godz", "górn", "gosp", "gr", "gram", "hist", "hiszp", "hr", "Hr", "hot", "id", "in", "im", "iron", "jn", "kard", "kat", "katol", "k.k", "kk", "kol", "kl", "k.p.a", "kpc", "k.p.c", "kpt", "kr", "k.r", "krak", "k.r.o", "kryt", "kult", "laic", "łac", "niem", "woj", "nb", "np", "Nb", "Np", "pol", "pow", "m.in", "pt", "ps", "Pt", "Ps", "cdn", "jw", "ryc", "rys", "Ryc", "Rys", "tj", "tzw", "Tzw", "tzn", "zob", "ang", "ub", "ul", "pw", "pn", "pl", "al", "k", "n", "ww", "wł", "ur", "zm", "żyd", "żarg", "żyw", "wył", "bp", "bp", "wyst", "tow", "Tow", "o", "sp", "Sp", "st", "spółdz", "Spółdz", "społ", "spółgł", "stoł", "stow", "Stoł", "Stow", "zn", "zew", "zewn", "zdr", "zazw", "zast", "zaw", "zał", "zal", "zam", "zak", "zakł", "zagr", "zach", "adw", "Adw", "lek", "Lek", "med", "mec", "Mec", "doc", "Doc", "dyw", "dyr", "Dyw", "Dyr", "inż", "Inż", "mgr", "Mgr", "dh", "dr", "Dh", "Dr", "p", "P", "red", "Red", "prof", "prok", "Prof", "Prok", "hab", "płk", "Płk", "nadkom", "Nadkom", "podkom", "Podkom", "ks", "Ks", "gen", "Gen", "por", "Por", "reż", "Reż", "przyp", "Przyp", "śp", "św", "śW", "Śp", "Św", "ŚW", "szer", "Szer", "tel", "poz", "pok", "oo", "oO", "Oo", "OO", "najśw", "Najśw", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Ś", "Ć", "Ż", "Ź", "Dz"), numericPrefixes = Set("nr", "Nr", "pkt", "str", "tab", "Tab", "ust", "par", "r", "l", "s")), Portuguese -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", // Roman Numerals. A dot after one of these is not a sentence break in Portuguese. "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix", "x", "xi", "xii", "xiii", "xiv", "xv", "xvi", "xvii", "xviii", "xix", "xx", // List of titles. These are often followed by upper-case names, but do not indicate sentence breaks. "Adj", "Adm", "Adv", "Art", "Ca", "Capt", "Cmdr", "Col", "Comdr", "Con", "Corp", "Cpl", "DR", "DRA", "Dr", "Dra", "Dras", "Drs", "Eng", "Enga", "Engas", "Engos", "Ex", "Exo", "Exmo", "Fig", "Gen", "Hosp", "Insp", "Lda", "MM", "MR", "MRS", "MS", "Maj", "Mrs", "Ms", "Msgr", "Op", "Ord", "Pfc", "Ph", "Prof", "Pvt", "Rep", "Reps", "Res", "Rev", "Rt", "Sen", "Sens", "Sfc", "Sgt", "Sr", "Sra", "Sras", "Srs", "Sto", "Supt", "Surg", "adj", "adm", "adv", "art", "cit", "col", "con", "corp", "cpl", "dr", "dra", "dras", "drs", "eng", "enga", "engas", "engos", "ex", "exo", "exmo", "fig", "op", "prof", "sr", "sra", "sras", "srs", "sto", // Miscellaneous symbols. "v", "vs", "i.e", "rev", "e.g", "Nos", "Nr"), numericPrefixes = Set( // Numbers only. These should only induce breaks when followed by a numeric sequence. "No", "Art", "pp")), Romanian -> NonBreakingPrefixes( prefixes = Set( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "dpdv", "etc", "șamd", "M.Ap.N", "dl", "Dl", "d-na", "D-na", "dvs", "Dvs", "pt", "Pt")), Russian -> NonBreakingPrefixes( prefixes = Set( "А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ы", "Ь", "Э", "Ю", "Я", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0гг", "1гг", "2гг", "3гг", "4гг", "5гг", "6гг", "7гг", "8гг", "9гг", "0г", "1г", "2г", "3г", "4г", "5г", "6г", "7г", "8г", "9г", "Xвв", "Vвв", "Iвв", "Lвв", "Mвв", "Cвв", "Xв", "Vв", "Iв", "Lв", "Mв", "Cв", "0м", "1м", "2м", "3м", "4м", "5м", "6м", "7м", "8м", "9м", "0мм", "1мм", "2мм", "3мм", "4мм", "5мм", "6мм", "7мм", "8мм", "9мм", "0см", "1см", "2см", "3см", "4см", "5см", "6см", "7см", "8см", "9см", "0дм", "1дм", "2дм", "3дм", "4дм", "5дм", "6дм", "7дм", "8дм", "9дм", "0л", "1л", "2л", "3л", "4л", "5л", "6л", "7л", "8л", "9л", "0км", "1км", "2км", "3км", "4км", "5км", "6км", "7км", "8км", "9км", "0га", "1га", "2га", "3га", "4га", "5га", "6га", "7га", "8га", "9га", "0кг", "1кг", "2кг", "3кг", "4кг", "5кг", "6кг", "7кг", "8кг", "9кг", "0т", "1т", "2т", "3т", "4т", "5т", "6т", "7т", "8т", "9т", "0г", "1г", "2г", "3г", "4г", "5г", "6г", "7г", "8г", "9г", "0мг", "1мг", "2мг", "3мг", "4мг", "5мг", "6мг", "7мг", "8мг", "9мг", "бульв", "в", "вв", "г", "га", "гг", "гл", "гос", "д", "дм", "доп", "др", "е", "ед", "ед", "зам", "и", "инд", "исп", "Исп", "к", "кап", "кг", "кв", "кл", "км", "кол", "комн", "коп", "куб", "л", "лиц", "лл", "м", "макс", "мг", "мин", "мл", "млн", "млрд", "мм", "н", "наб", "нач", "неуд", "ном", "о", "обл", "обр", "общ", "ок", "ост", "отл", "п", "пер", "перераб", "пл", "пос", "пр", "просп", "проф", "р", "ред", "руб", "с", "сб", "св", "см", "соч", "ср", "ст", "стр", "т", "тел", "Тел", "тех", "тт", "туп", "тыс", "уд", "ул", "уч", "физ", "х", "хор", "ч", "чел", "шт", "экз", "э")), Slovak -> NonBreakingPrefixes( prefixes = Set( "Bc", "Mgr", "RNDr", "PharmDr", "PhDr", "JUDr", "PaedDr", "ThDr", "Ing", "MUDr", "MDDr", "MVDr", "Dr", "ThLic", "PhD", "ArtD", "ThDr", "Dr", "DrSc", "CSs", "prof", "obr", "Obr", "Č", "č", "absol", "adj", "admin", "adr", "Adr", "adv", "advok", "afr", "ak", "akad", "akc", "akuz", "et", "al", "alch", "amer", "anat", "angl", "Angl", "anglosas", "anorg", "ap", "apod", "arch", "archeol", "archit", "arg", "art", "astr", "astrol", "astron", "atp", "atď", "austr", "Austr", "aut", "belg", "Belg", "bibl", "Bibl", "biol", "bot", "bud", "bás", "býv", "cest", "chem", "cirk", "csl", "čs", "Čs", "dat", "dep", "det", "dial", "diaľ", "dipl", "distrib", "dokl", "dosl", "dopr", "dram", "duš", "dv", "dvojčl", "dór", "ekol", "ekon", "el", "elektr", "elektrotech", "energet", "epic", "est", "etc", "etonym", "eufem", "európ", "Európ", "ev", "evid", "expr", "fa", "fam", "farm", "fem", "feud", "fil", "filat", "filoz", "fi", "fon", "form", "fot", "fr", "Fr", "franc", "Franc", "fraz", "fut", "fyz", "fyziol", "garb", "gen", "genet", "genpor", "geod", "geogr", "geol", "geom", "germ", "gr", "Gr", "gréc", "Gréc", "gréckokat", "hebr", "herald", "hist", "hlav", "hosp", "hromad", "hud", "hypok", "ident", "i.e", "ident", "imp", "impf", "indoeur", "inf", "inform", "instr", "int", "interj", "inšt", "inštr", "iron", "jap", "Jap", "jaz", "jedn", "juhoamer", "juhových", "juhozáp", "juž", "kanad", "Kanad", "kanc", "kapit", "kpt", "kart", "katastr", "knih", "kniž", "komp", "konj", "konkr", "kozmet", "krajč", "kresť", "kt", "kuch", "lat", "latinskoamer", "lek", "lex", "lingv", "lit", "litur", "log", "lok", "max", "Max", "maď", "Maď", "medzinár", "mest", "metr", "mil", "Mil", "min", "Min", "miner", "ml", "mld", "mn", "mod", "mytol", "napr", "nar", "Nar", "nasl", "nedok", "neg", "negat", "neklas", "nem", "Nem", "neodb", "neos", "neskl", "nesklon", "nespis", "nespráv", "neved", "než", "niekt", "niž", "nom", "náb", "nákl", "námor", "nár", "obch", "obj", "obv", "obyč", "obč", "občian", "odb", "odd", "ods", "ojed", "okr", "Okr", "opt", "opyt", "org", "os", "osob", "ot", "ovoc", "par", "part", "pejor", "pers", "pf", "Pf ", "P.f", "p.f", "pl", "Plk", "pod", "podst", "pokl", "polit", "politol", "polygr", "pomn", "popl", "por", "porad", "porov", "posch", "potrav", "použ", "poz", "pozit", "poľ", "poľno", "poľnohosp", "poľov", "pošt", "pož", "prac", "predl", "pren", "prep", "preuk", "priezv", "Priezv", "privl", "prof", "práv", "príd", "príj", "prík", "príp", "prír", "prísl", "príslov", "príč", "psych", "publ", "pís", "písm", "pôv", "refl", "reg", "rep", "resp", "rozk", "rozlič", "rozpráv", "roč", "Roč", "ryb", "rádiotech", "rím", "samohl", "semest", "sev", "severoamer", "severových", "severozáp", "sg", "skr", "skup", "sl", "Sloven", "soc", "soch", "sociol", "sp", "spol", "Spol", "spoloč", "spoluhl", "správ", "spôs", "st", "star", "starogréc", "starorím", "s.r.o", "stol", "stor", "str", "stredoamer", "stredoškol", "subj", "subst", "superl", "sv", "sz", "súkr", "súp", "súvzť", "tal", "Tal", "tech", "tel", "Tel", "telef", "teles", "telev", "teol", "trans", "turist", "tuzem", "typogr", "tzn", "tzv", "ukaz", "ul", "Ul", "umel", "univ", "ust", "ved", "vedľ", "verb", "veter", "vin", "viď", "vl", "vod", "vodohosp", "pnl", "vulg", "vyj", "vys", "vysokoškol", "vzťaž", "vôb", "vých", "výd", "výrob", "výsk", "výsl", "výtv", "výtvar", "význ", "včel", "vš", "všeob", "zahr", "zar", "zariad", "zast", "zastar", "zastaráv", "zb", "zdravot", "združ", "zjemn", "zlat", "zn", "Zn", "zool", "zr", "zried", "zv", "záhr", "zák", "zákl", "zám", "záp", "západoeur", "zázn", "územ", "účt", "čast", "čes", "Čes", "čl", "čísl", "živ", "pr", "fak", "Kr", "p.n.l", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")), Slovenian -> NonBreakingPrefixes( prefixes = Set( "dr", "Dr", "itd", "itn", "d", "jan", "Jan", "feb", "Feb", "mar", "Mar", "apr", "Apr", "jun", "Jun", "jul", "Jul", "avg", "Avg", "sept", "Sept", "sep", "Sep", "okt", "Okt", "nov", "Nov", "dec", "Dec", "tj", "Tj", "npr", "Npr", "sl", "Sl", "op", "Op", "gl", "Gl", "oz", "Oz", "prev", "dipl", "ing", "prim", "Prim", "cf", "Cf", "gl", "Gl", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"), numericPrefixes = Set("št", "Št")), Swedish -> NonBreakingPrefixes( prefixes = Set( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AB", "G", "VG", "dvs", "etc", "from", "iaf", "jfr", "kl", "kr", "mao", "mfl", "mm", "osv", "pga", "tex", "tom", "vs")), Spanish -> NonBreakingPrefixes( prefixes = Set( // Any single upper case letter followed by a period is not at the end of a sentence (excluding "I" // occasionally, but we leave it in) usually upper case letters are initials in a name. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", // Period-final abbreviation list from http://www.ctspanish.com/words/abbreviations.htm. "A.C", "Apdo", "Av", "Bco", "CC.AA", "Da", "Dep", "Dn", "Dr", "Dra", "EE.UU", "Excmo", "FF.CC", "Fil ", "Gral", "J.C", "Let", "Lic", "N.B", "P.D", "PV.P", "Prof", "Pts", "Rte", "S.A", "S.A.R", "S.E", "S.L", "S.R.C", "Sr", "Sra", "Srta", "Sta", "Sto", "T.V.E", "Tel", "Ud", "Uds", "V.B", "V.E", "Vd", "Vds", "a/c", "adj", "admón", "afmo", "apdo", "av", "c", "c.f", "c.g", "cap", "cm", "cta", "dcha", "doc", "ej", "entlo", "esq", "etc", "f.c", "gr ", "grs", "izq", "kg", "km", "mg", "mm", "núm", "núm", "p", "p.a", "p.ej", "ptas", "pág ", "págs", "pág", "págs", "q.e.g.e", "q.e.s.m", "s", "s.s.s", "vid", "vol") ), Tamil -> NonBreakingPrefixes( prefixes = Set( "அ", "ஆ", "இ", "ஈ", "உ", "ஊ", "எ", "ஏ", "ஐ", "ஒ", "ஓ", "ஔ", "ஃ", "க", "கா", "கி", "கீ", "கு", "கூ", "கெ", "கே", "கை", "கொ", "கோ", "கௌ", "க்", "ச", "சா", "சி", "சீ", "சு", "சூ", "செ", "சே", "சை", "சொ", "சோ", "சௌ", "ச்", "ட", "டா", "டி", "டீ", "டு", "டூ", "டெ", "டே", "டை", "டொ", "டோ", "டௌ", "ட்", "த", "தா", "தி", "தீ", "து", "தூ", "தெ", "தே", "தை", "தொ", "தோ", "தௌ", "த்", "ப", "பா", "பி", "பீ", "பு", "பூ", "பெ", "பே", "பை", "பொ", "போ", "பௌ", "ப்", "ற", "றா", "றி", "றீ", "று", "றூ", "றெ", "றே", "றை", "றொ", "றோ", "றௌ", "ற்", "ய", "யா", "யி", "யீ", "யு", "யூ", "யெ", "யே", "யை", "யொ", "யோ", "யௌ", "ய்", "ர", "ரா", "ரி", "ரீ", "ரு", "ரூ", "ரெ", "ரே", "ரை", "ரொ", "ரோ", "ரௌ", "ர்", "ல", "லா", "லி", "லீ", "லு", "லூ", "லெ", "லே", "லை", "லொ", "லோ", "லௌ", "ல்", "வ", "வா", "வி", "வீ", "வு", "வூ", "வெ", "வே", "வை", "வொ", "வோ", "வௌ", "வ்", "ள", "ளா", "ளி", "ளீ", "ளு", "ளூ", "ளெ", "ளே", "ளை", "ளொ", "ளோ", "ளௌ", "ள்", "ழ", "ழா", "ழி", "ழீ", "ழு", "ழூ", "ழெ", "ழே", "ழை", "ழொ", "ழோ", "ழௌ", "ழ்", "ங", "ஙா", "ஙி", "ஙீ", "ஙு", "ஙூ", "ஙெ", "ஙே", "ஙை", "ஙொ", "ஙோ", "ஙௌ", "ங்", "ஞ", "ஞா", "ஞி", "ஞீ", "ஞு", "ஞூ", "ஞெ", "ஞே", "ஞை", "ஞொ", "ஞோ", "ஞௌ", "ஞ்", "ண", "ணா", "ணி", "ணீ", "ணு", "ணூ", "ணெ", "ணே", "ணை", "ணொ", "ணோ", "ணௌ", "ண்", "ந", "நா", "நி", "நீ", "நு", "நூ", "நெ", "நே", "நை", "நொ", "நோ", "நௌ", "ந்", "ம", "மா", "மி", "மீ", "மு", "மூ", "மெ", "மே", "மை", "மொ", "மோ", "மௌ", "ம்", "ன", "னா", "னி", "னீ", "னு", "னூ", "னெ", "னே", "னை", "னொ", "னோ", "னௌ", "ன்", "திரு", "திருமதி", "வண", "கௌரவ", "உ.ம்", "Nos", "Nr"), numericPrefixes = Set( // Numbers only. These should only induce breaks when followed by a numeric sequence. "No", "Art", "pp")) ).withDefaultValue(NonBreakingPrefixes()) }
63,542
83.274536
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/NoTokenizer.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import better.files.File /** Represents a dummy tokenizer that does nothing. * * @author Emmanouil Antonios Platanios */ object NoTokenizer extends Tokenizer { override def tokenizedFile(originalFile: File): File = originalFile override def tokenize(sentence: String, language: Language): String = sentence override def tokenizeCorpus(file: File, language: Language, bufferSize: Int = 8192): File = file override def toString: String = "t:none" }
1,193
35.181818
98
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/Normalizer.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.Language._ import org.platanios.symphony.mt.data.{newReader, newWriter} import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import scala.util.matching.Regex /** * @author Emmanouil Antonios Platanios */ object Normalizer extends FileProcessor { private val logger = Logger(LoggerFactory.getLogger("Data / Normalizer")) private val replacementRegexSeq: Seq[(Regex, String)] = Seq( ("""À""".r, "À"), ("""Ã""".r, "Ã"), ("""Ả""".r, "Ả"), ("""Á""".r, "Á"), ("""Ạ""".r, "Ạ"), ("""Ằ""".r, "Ằ"), ("""Ẵ""".r, "Ẵ"), ("""Ẳ""".r, "Ẳ"), ("""Ắ""".r, "Ắ"), ("""Ặ""".r, "Ặ"), ("""Ầ""".r, "Ầ"), ("""Ẫ""".r, "Ẫ"), ("""Ẩ""".r, "Ẩ"), ("""Ấ""".r, "Ấ"), ("""Ậ""".r, "Ậ"), ("""Ỳ""".r, "Ỳ"), ("""Ỹ""".r, "Ỹ"), ("""Ỷ""".r, "Ỷ"), ("""Ý""".r, "Ý"), ("""Ỵ""".r, "Ỵ"), ("""Ì""".r, "Ì"), ("""Ĩ""".r, "Ĩ"), ("""Ỉ""".r, "Ỉ"), ("""Í""".r, "Í"), ("""Ị""".r, "Ị"), ("""Ù""".r, "Ù"), ("""Ũ""".r, "Ũ"), ("""Ủ""".r, "Ủ"), ("""Ú""".r, "Ú"), ("""Ụ""".r, "Ụ"), ("""Ừ""".r, "Ừ"), ("""Ữ""".r, "Ữ"), ("""Ử""".r, "Ử"), ("""Ứ""".r, "Ứ"), ("""Ự""".r, "Ự"), ("""È""".r, "È"), ("""Ẽ""".r, "Ẽ"), ("""Ẻ""".r, "Ẻ"), ("""É""".r, "É"), ("""Ẹ""".r, "Ẹ"), ("""Ề""".r, "Ề"), ("""Ễ""".r, "Ễ"), ("""Ể""".r, "Ể"), ("""Ế""".r, "Ế"), ("""Ệ""".r, "Ệ"), ("""Ò""".r, "Ò"), ("""Õ""".r, "Õ"), ("""Ỏ""".r, "Ỏ"), ("""Ó""".r, "Ó"), ("""Ọ""".r, "Ọ"), ("""Ờ""".r, "Ờ"), ("""Ỡ""".r, "Ỡ"), ("""Ở""".r, "Ở"), ("""Ớ""".r, "Ớ"), ("""Ợ""".r, "Ợ"), ("""Ồ""".r, "Ồ"), ("""Ỗ""".r, "Ỗ"), ("""Ổ""".r, "Ổ"), ("""Ố""".r, "Ố"), ("""Ộ""".r, "Ộ"), ("""ÒA""".r, "OÀ"), ("""ÕA""".r, "OÃ"), ("""ỎA""".r, "OẢ"), ("""ÓA""".r, "OÁ"), ("""ỌA""".r, "OẠ"), ("""ÒE""".r, "OÈ"), ("""ÕE""".r, "OẼ"), ("""ỎE""".r, "OẺ"), ("""ÓE""".r, "OÉ"), ("""ỌE""".r, "OẸ"), ("""ÙY""".r, "UỲ"), ("""ŨY""".r, "UỸ"), ("""ỦY""".r, "UỶ"), ("""ÚY""".r, "UÝ"), ("""ỤY""".r, "UỴ"), ("""à""".r, "à"), ("""ã""".r, "ã"), ("""ả""".r, "ả"), ("""á""".r, "á"), ("""ạ""".r, "ạ"), ("""ằ""".r, "ằ"), ("""ẵ""".r, "ẵ"), ("""ẳ""".r, "ẳ"), ("""ắ""".r, "ắ"), ("""ặ""".r, "ặ"), ("""ầ""".r, "ầ"), ("""ẫ""".r, "ẫ"), ("""ẩ""".r, "ẩ"), ("""ấ""".r, "ấ"), ("""ậ""".r, "ậ"), ("""ỳ""".r, "ỳ"), ("""ỹ""".r, "ỹ"), ("""ỷ""".r, "ỷ"), ("""ý""".r, "ý"), ("""ỵ""".r, "ỵ"), ("""ì""".r, "ì"), ("""ĩ""".r, "ĩ"), ("""ỉ""".r, "ỉ"), ("""í""".r, "í"), ("""ị""".r, "ị"), ("""ù""".r, "ù"), ("""ũ""".r, "ũ"), ("""ủ""".r, "ủ"), ("""ú""".r, "ú"), ("""ụ""".r, "ụ"), ("""ừ""".r, "ừ"), ("""ữ""".r, "ữ"), ("""ử""".r, "ử"), ("""ứ""".r, "ứ"), ("""ự""".r, "ự"), ("""è""".r, "è"), ("""ẽ""".r, "ẽ"), ("""ẻ""".r, "ẻ"), ("""é""".r, "é"), ("""ẹ""".r, "ẹ"), ("""ề""".r, "ề"), ("""ễ""".r, "ễ"), ("""ể""".r, "ể"), ("""ế""".r, "ế"), ("""ệ""".r, "ệ"), ("""ò""".r, "ò"), ("""õ""".r, "õ"), ("""ỏ""".r, "ỏ"), ("""ó""".r, "ó"), ("""ọ""".r, "ọ"), ("""ờ""".r, "ờ"), ("""ỡ""".r, "ỡ"), ("""ở""".r, "ở"), ("""ớ""".r, "ớ"), ("""ợ""".r, "ợ"), ("""ồ""".r, "ồ"), ("""ỗ""".r, "ỗ"), ("""ổ""".r, "ổ"), ("""ố""".r, "ố"), ("""ộ""".r, "ộ"), ("""òa""".r, "oà"), ("""õa""".r, "oã"), ("""ỏa""".r, "oả"), ("""óa""".r, "oá"), ("""ọa""".r, "oạ"), ("""òe""".r, "oè"), ("""õe""".r, "oẽ"), ("""ỏe""".r, "oẻ"), ("""óe""".r, "oé"), ("""ọe""".r, "oẹ"), ("""ùy""".r, "uỳ"), ("""ũy""".r, "uỹ"), ("""ủy""".r, "uỷ"), ("""úy""".r, "uý"), ("""ụy""".r, "uỵ"), ("""aó""".r, "áo"), ("""òA""".r, "oà"), ("""õA""".r, "oã"), ("""ỏA""".r, "oả"), ("""óA""".r, "oá"), ("""ọA""".r, "oạ"), ("""òE""".r, "oè"), ("""õE""".r, "oẽ"), ("""ỏE""".r, "oẻ"), ("""óE""".r, "oé"), ("""ọE""".r, "oẹ"), ("""ùY""".r, "uỳ"), ("""ũY""".r, "uỹ"), ("""ủY""".r, "uỷ"), ("""úY""".r, "uý"), ("""ụY""".r, "uỵ"), ("""Òa""".r, "Oà"), ("""Õa""".r, "Oã"), ("""Ỏa""".r, "Oả"), ("""Óa""".r, "Oá"), ("""Ọa""".r, "Oạ"), ("""Òe""".r, "Oè"), ("""Õe""".r, "Oẽ"), ("""Ỏe""".r, "Oẻ"), ("""Óe""".r, "Oé"), ("""Ọe""".r, "Oẹ"), ("""Ùy""".r, "Uỳ"), ("""Ũy""".r, "Uỹ"), ("""Ủy""".r, "Uỷ"), ("""Úy""".r, "Uý"), ("""Ụy""".r, "Uỵ")) private val whitespaceRegex : Regex = """\s+""".r private val regexUnicodeNumber0: Regex = """0""".r private val regexUnicodeNumber2: Regex = """2""".r private val regexUnicodeNumber3: Regex = """3""".r private val regexUnicodeNumber4: Regex = """4""".r private val regexUnicodeNumber5: Regex = """5""".r private val regexUnicodeNumber6: Regex = """6""".r private val regexUnicodeNumber7: Regex = """7""".r private val regexUnicodeNumber8: Regex = """8""".r private val regexUnicodeNumber9: Regex = """9""".r private val unicodeRegex1 : Regex = """,|、""".r private val unicodeRegex2 : Regex = """。 *|. *""".r private val unicodeRegex3 : Regex = """‘|‚|’|''|´´|”|“|《|》|1|」|「""".r private val unicodeRegex4 : Regex = """∶|:""".r private val unicodeRegex5 : Regex = """?""".r private val unicodeRegex6 : Regex = """)""".r private val unicodeRegex7 : Regex = """!""".r private val unicodeRegex8 : Regex = """(""".r private val unicodeRegex9 : Regex = """;""".r private val unicodeRegex10 : Regex = """~""".r private val unicodeRegex11 : Regex = """’""".r private val unicodeRegex12 : Regex = """…|…""".r private val unicodeRegex13 : Regex = """〈""".r private val unicodeRegex14 : Regex = """〉""".r private val unicodeRegex15 : Regex = """【""".r private val unicodeRegex16 : Regex = """】""".r private val unicodeRegex17 : Regex = """%""".r private val regexEn : Regex = """\"([,\.]+)""".r private val regex1 : Regex = """\(""".r private val regex2 : Regex = """\)""".r private val regex3 : Regex = """\) ([\.\!\:\?\;\,])""".r private val regex4 : Regex = """\( """.r private val regex5 : Regex = """ \)""".r private val regex6 : Regex = """(\d) \%""".r private val regex7 : Regex = """ :""".r private val regex8 : Regex = """ ;""".r private val regex9 : Regex = """\`""".r private val regex10 : Regex = """\'\'""".r private val regex11 : Regex = """„|“|”""".r private val regex12 : Regex = """–|━""".r private val regex13 : Regex = """—""".r private val regex14 : Regex = """´""".r private val regex15 : Regex = """([a-zA-Z])‘([a-zA-Z])""".r private val regex16 : Regex = """([a-zA-Z])’([a-zA-Z])""".r private val regex19 : Regex = """ « """.r private val regex20 : Regex = """« |«""".r private val regex21 : Regex = """ » """.r private val regex22 : Regex = """ »|»""".r private val regex23 : Regex = """ \%""".r private val regex24 : Regex = """nº """.r private val regex25 : Regex = """ ºC""".r private val regex26 : Regex = """ cm""".r private val regex27 : Regex = """ \?""".r private val regex28 : Regex = """ \!""".r private val regex29 : Regex = """,\"""".r private val regex30 : Regex = """(\.+)\"(\s*[^<])""".r private val regex31 : Regex = """(\d) (\d)""".r override def process(file: File, language: Language): File = normalizeCorpus(file, language) def normalizedFile(originalFile: File): File = { val fileName = originalFile.nameWithoutExtension(includeAll = false) + s".normalized${originalFile.extension().get}" originalFile.sibling(fileName) } def normalize(sentence: String, language: Language): String = { var normalized = language match { case Vietnamese => replacementRegexSeq.foldLeft(sentence)((s, r) => r._1.replaceAllIn(s, r._2)) case _ => sentence } normalized = regexUnicodeNumber0.replaceAllIn(normalized, "0") normalized = regexUnicodeNumber2.replaceAllIn(normalized, "2") normalized = regexUnicodeNumber3.replaceAllIn(normalized, "3") normalized = regexUnicodeNumber4.replaceAllIn(normalized, "4") normalized = regexUnicodeNumber5.replaceAllIn(normalized, "5") normalized = regexUnicodeNumber6.replaceAllIn(normalized, "6") normalized = regexUnicodeNumber7.replaceAllIn(normalized, "7") normalized = regexUnicodeNumber8.replaceAllIn(normalized, "8") normalized = regexUnicodeNumber9.replaceAllIn(normalized, "9") normalized = unicodeRegex1.replaceAllIn(normalized, ",") normalized = unicodeRegex2.replaceAllIn(normalized, ". ") normalized = unicodeRegex3.replaceAllIn(normalized, "\"") normalized = unicodeRegex4.replaceAllIn(normalized, ":") normalized = unicodeRegex5.replaceAllIn(normalized, "?") normalized = unicodeRegex6.replaceAllIn(normalized, ")") normalized = unicodeRegex7.replaceAllIn(normalized, "!") normalized = unicodeRegex8.replaceAllIn(normalized, "(") normalized = unicodeRegex9.replaceAllIn(normalized, ";") normalized = unicodeRegex10.replaceAllIn(normalized, "~") normalized = unicodeRegex11.replaceAllIn(normalized, "'") normalized = unicodeRegex12.replaceAllIn(normalized, "...") normalized = unicodeRegex13.replaceAllIn(normalized, "<") normalized = unicodeRegex14.replaceAllIn(normalized, ">") normalized = unicodeRegex15.replaceAllIn(normalized, "[") normalized = unicodeRegex16.replaceAllIn(normalized, "]") normalized = unicodeRegex17.replaceAllIn(normalized, "%") normalized = regex1.replaceAllIn(normalized, " (") normalized = regex2.replaceAllIn(normalized, ") ") normalized = whitespaceRegex.replaceAllIn(normalized, " ") normalized = regex3.replaceAllIn(normalized, ")$1") normalized = regex4.replaceAllIn(normalized, "(") normalized = regex5.replaceAllIn(normalized, ")") normalized = regex6.replaceAllIn(normalized, "$1%") normalized = regex7.replaceAllIn(normalized, ":") normalized = regex8.replaceAllIn(normalized, ";") normalized = regex9.replaceAllIn(normalized, "'") normalized = regex10.replaceAllIn(normalized, " \" ") normalized = regex11.replaceAllIn(normalized, "\"") normalized = regex12.replaceAllIn(normalized, "-") normalized = regex13.replaceAllIn(normalized, " - ") normalized = whitespaceRegex.replaceAllIn(normalized, " ") normalized = regex14.replaceAllIn(normalized, "'") normalized = regex15.replaceAllIn(normalized, "$1'$2") normalized = regex16.replaceAllIn(normalized, "$1'$2") normalized = regex19.replaceAllIn(normalized, " \"") normalized = regex20.replaceAllIn(normalized, "\"") normalized = regex21.replaceAllIn(normalized, "\" ") normalized = regex22.replaceAllIn(normalized, "\"") normalized = regex23.replaceAllIn(normalized, "%") normalized = regex24.replaceAllIn(normalized, "nº") normalized = regex25.replaceAllIn(normalized, "ºC") normalized = regex26.replaceAllIn(normalized, "cm") normalized = regex27.replaceAllIn(normalized, "?") normalized = regex28.replaceAllIn(normalized, "!") normalized = regex7.replaceAllIn(normalized, ":") normalized = regex8.replaceAllIn(normalized, ";") normalized = whitespaceRegex.replaceAllIn(normalized, " ") if (language == English) { normalized = regexEn.replaceAllIn(normalized, "$1\"") } else if (language != Czech) { normalized = regex29.replaceAllIn(normalized, "\",") normalized = regex30.replaceAllIn(normalized, "\"$1$2") } if (language == German || language == Spanish || language == Czech || language == French) normalized = regex31.replaceAllIn(normalized, "$1,$2") else normalized = regex31.replaceAllIn(normalized, "$1.$2") normalized } def normalizeCorpus(file: File, language: Language): File = { val normalized = normalizedFile(file) if (normalized.notExists) { logger.info(s"Normalizing '$file'.") val tokenizedWriter = newWriter(normalized) newReader(file).lines().toAutoClosedIterator.foreach(sentence => { tokenizedWriter.write(s"${normalize(sentence, language)}\n") }) tokenizedWriter.flush() tokenizedWriter.close() logger.info(s"Created normalized file '$normalized'.") } normalized } }
13,018
55.359307
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/NoCleaner.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import better.files.File /** Represents a dummy cleaner that does nothing. * * @author Emmanouil Antonios Platanios */ object NoCleaner extends Cleaner { override def cleanFile(originalFile: File): File = originalFile override def cleanSentencePair(srcSentence: String, tgtSentence: String): Option[(String, String)] = { Some((srcSentence, tgtSentence)) } override def cleanCorporaPair(srcFile: File, tgtFile: File, bufferSize: Int = 8192): (File, File) = { (srcFile, tgtFile) } override def toString: String = "c:none" }
1,239
32.513514
104
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/SGMConverter.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{newReader, newWriter} import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import scala.collection.JavaConverters._ import scala.util.matching.Regex /** * @author Emmanouil Antonios Platanios */ object SGMConverter extends FileProcessor { private val logger = Logger(LoggerFactory.getLogger("Data / SGM Converter")) private val startRegex : Regex = """(?i)<seg[^>]+>\s*$""".r private val startCaptureRegex : Regex = """(?i)<seg[^>]+>\s*(.*)\s*$""".r private val startStopCaptureRegex: Regex = """(?i)<seg[^>]+>\s*(.*)\s*<\/seg>""".r private val whitespaceRegex : Regex = """\s+""".r override def process(file: File, language: Language): File = { val textFile = convertedFile(file) if (textFile.notExists) { logger.info(s"Converting SGM file '$file' to text file '$textFile'.") val reader = newReader(file) val writer = newWriter(textFile) val linesIterator = reader.lines().iterator().asScala while (linesIterator.nonEmpty) { var line = linesIterator.next() while (linesIterator.hasNext && startRegex.findFirstIn(line).isDefined) line += linesIterator.next() while (linesIterator.hasNext && startCaptureRegex.findFirstIn(line).isDefined && startStopCaptureRegex.findFirstIn(line).isEmpty) line += linesIterator.next() startStopCaptureRegex.findFirstMatchIn(line) match { case Some(sentenceMatch) => var sentence = sentenceMatch.group(1) sentence = whitespaceRegex.replaceAllIn(sentence.trim, " ") writer.write(s"$sentence\n") case None => () } } writer.flush() writer.close() logger.info(s"Converted SGM file '$file' to text file '$textFile'.") } textFile } private def convertedFile(originalFile: File): File = { originalFile.sibling(originalFile.nameWithoutExtension(includeAll = false)) } }
2,762
36.849315
84
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/TSVConverter.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data._ import better.files.File import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import scala.collection.JavaConverters._ import scala.util.Try /** * @author Emmanouil Antonios Platanios */ object TSVConverter extends FileProcessor { private val logger = Logger(LoggerFactory.getLogger("Data / TSV Converter")) private val MISSING_SENTENCE: String = "__NULL__" override def processPair(file1: File, file2: File, language1: Language, language2: Language): (File, File) = { assert(file1 == file2, "The TSV converter assumes that the data for all languages is stored in the same file.") val reader = newReader(file1) val linesIterator = reader.lines().iterator().asScala val header = linesIterator.next() val languages = header.split('\t').tail.map(l => Try(Language.fromAbbreviation(l)).getOrElse(null)) // TODO: [DATA] This is very hacky (because of "calv" language". val language1Index = languages.indexOf(language1) + 1 // We add one to account for the first column ("talk_name"). val language2Index = languages.indexOf(language2) + 1 val textFileNamePrefix = s"${file1.nameWithoutExtension}.${language1.abbreviation}-${language2.abbreviation}" val textFile1 = file1.sibling(s"$textFileNamePrefix.${language1.abbreviation}") val textFile2 = file2.sibling(s"$textFileNamePrefix.${language2.abbreviation}") if (textFile1.notExists || textFile2.notExists) { logger.info(s"Converting TSV file '$file1' to text files '$textFile1' and '$textFile2'.") val writer1 = newWriter(textFile1) val writer2 = newWriter(textFile2) while (linesIterator.nonEmpty) { val line = linesIterator.next() val lineParts = line.split('\t') val language1Sentence = lineParts(language1Index) val language2Sentence = lineParts(language2Index) if (language1Sentence != MISSING_SENTENCE && language2Sentence != MISSING_SENTENCE) { writer1.write(s"${lineParts(language1Index)}\n") writer2.write(s"${lineParts(language2Index)}\n") } } writer1.flush() writer2.flush() writer1.close() writer2.close() logger.info(s"Converted TSV file '$file1' to text files '$textFile1' and '$textFile2'.") } (textFile1, textFile2) } }
3,065
42.8
168
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/MosesCleaner.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import better.files.File import java.nio.charset.StandardCharsets import scala.util.matching.Regex /** * @author Emmanouil Antonios Platanios */ class MosesCleaner protected ( val minSentenceLength: Int = -1, val maxSentenceLength: Int = -1, val maxWordLength: Int = -1, val lowerCase: Boolean = false ) extends Cleaner { protected val ignoredRegex : Regex = """\|""".r protected val whitespaceRegex : Regex = """\s+""".r protected val maxWordLengthRegex: Regex = s"""[\\S]{${maxWordLength + 1},}""".r override def cleanFile(originalFile: File): File = { val fileName = originalFile.nameWithoutExtension(includeAll = false) originalFile.sibling(fileName + s".clean:moses${originalFile.extension().get}") } override def cleanSentencePair(srcSentence: String, tgtSentence: String): Option[(String, String)] = { var src = srcSentence.trim var tgt = tgtSentence.trim // Fix spaces. src = whitespaceRegex.replaceAllIn(src, " ") tgt = whitespaceRegex.replaceAllIn(tgt, " ") // Decide whether to keep the pair or not. var keep = src != "" && tgt != "" if (minSentenceLength >= 0 || maxSentenceLength >= 0) { val srcNumWords = whitespaceRegex.split(src).length val tgtNumWords = whitespaceRegex.split(tgt).length keep &&= minSentenceLength < 0 || (srcNumWords >= minSentenceLength && tgtNumWords >= minSentenceLength) keep &&= maxSentenceLength < 0 || (srcNumWords <= maxSentenceLength && tgtNumWords <= maxSentenceLength) } // Check for the maximum word length, if necessary. if (maxWordLength >= 0) { keep &&= maxWordLengthRegex.findFirstIn(src).isEmpty keep &&= maxWordLengthRegex.findFirstIn(tgt).isEmpty } if (!keep) { None } else { // Lowercase, if necessary. if (lowerCase) { src = src.toLowerCase tgt = tgt.toLowerCase } // Remove non-UTF8 characters. src = StandardCharsets.UTF_8.decode(StandardCharsets.UTF_8.encode(src)).toString tgt = StandardCharsets.UTF_8.decode(StandardCharsets.UTF_8.encode(tgt)).toString Some((src, tgt)) } } override def toString: String = "c:moses" } object MosesCleaner { def apply( minSentenceLength: Int = -1, maxSentenceLength: Int = -1, maxWordLength: Int = -1, lowerCase: Boolean = false ): MosesCleaner = { new MosesCleaner( minSentenceLength, maxSentenceLength, maxWordLength, lowerCase) } }
3,197
31.30303
110
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/MTEval13Tokenizer.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import better.files.File import scala.util.matching.Regex /** Tokenizer used by the official `mteval-v13a.perl` script. * * The code in this class is a Scala translation of the * [original script code](https://github.com/moses-smt/mosesdecoder/blob/master/scripts/generic/mteval-v13a.pl). * * @param preserveCase If `true`, case will be preserved. * * @author Emmanouil Antonios Platanios */ case class MTEval13Tokenizer( preserveCase: Boolean = true ) extends Tokenizer { private val skippedRegex : Regex = """<skipped>""".r private val endOfLineHyphenationRegex : Regex = """-\n""".r private val joinLinesRegex : Regex = """\n""".r private val sgmlQuoteRegex : Regex = """&quot;""".r private val sgmlAmpersandRegex : Regex = """&amp;""".r private val sgmlLtRegex : Regex = """&lt;""".r private val sgmlGtRegex : Regex = """&gt;""".r private val punctuationRegex : Regex = """([\{-\~\[-\` -\&\(-\+\:-\@\/])""".r private val periodCommaUnlessPrecededByDigitRegex: Regex = """([^0-9])([\.,])""".r private val periodCommaUnlessFollowedByDigitRegex: Regex = """([\.,])([^0-9])""".r private val dashPrecededByDigitRegex : Regex = """([0-9])(-)""".r private val whitespaceRegex : Regex = """\s+""".r private val leadingWhitespaceRegex : Regex = """^\s+""".r private val trailingWhitespaceRegex : Regex = """\s+$""".r override def tokenizedFile(originalFile: File): File = { val fileName = originalFile.nameWithoutExtension(includeAll = false) originalFile.sibling(fileName + s".tok:mteval13${originalFile.extension().get}") } override def tokenize(sentence: String, language: Language): String = { var tokenized = sentence.trim // Language-independent part. tokenized = skippedRegex.replaceAllIn(tokenized, "") tokenized = endOfLineHyphenationRegex.replaceAllIn(tokenized, "") tokenized = joinLinesRegex.replaceAllIn(tokenized, " ") tokenized = sgmlQuoteRegex.replaceAllIn(tokenized, "\"") tokenized = sgmlAmpersandRegex.replaceAllIn(tokenized, "&") tokenized = sgmlLtRegex.replaceAllIn(tokenized, "<") tokenized = sgmlGtRegex.replaceAllIn(tokenized, ">") // Language-dependent part (assuming Western languages). tokenized = s" $tokenized " if (!preserveCase) tokenized = tokenized.toLowerCase tokenized = punctuationRegex.replaceAllIn(tokenized, " $1 ") tokenized = periodCommaUnlessPrecededByDigitRegex.replaceAllIn(tokenized, "$1 $2 ") tokenized = periodCommaUnlessFollowedByDigitRegex.replaceAllIn(tokenized, " $1 $2") tokenized = dashPrecededByDigitRegex.replaceAllIn(tokenized, "$1 $2 ") tokenized = whitespaceRegex.replaceAllIn(tokenized, " ") tokenized = leadingWhitespaceRegex.replaceAllIn(tokenized, "") tokenized = trailingWhitespaceRegex.replaceAllIn(tokenized, "") tokenized } override def toString: String = "t:mteval13" }
3,851
43.790698
113
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/FileProcessor.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import better.files._ /** * @author Emmanouil Antonios Platanios */ trait FileProcessor { def apply(file: File, language: Language): File = process(file, language) def apply(file1: File, file2: File, language1: Language, language2: Language): (File, File) = { processPair(file1, file2, language1, language2) } def process(file: File, language: Language): File = file def processPair(file1: File, file2: File, language1: Language, language2: Language): (File, File) = { (process(file1, language1), process(file2, language2)) } def >>(processor: FileProcessor): ComposedFileProcessor = { ComposedFileProcessor(this, processor) } } object NoFileProcessor extends FileProcessor case class ComposedFileProcessor(fileProcessors: FileProcessor*) extends FileProcessor { override def process(file: File, language: Language): File = { fileProcessors.foldLeft(file)((f, p) => p.process(f, language)) } override def processPair(file1: File, file2: File, language1: Language, language2: Language): (File, File) = { fileProcessors.foldLeft((file1, file2))((f, p) => p.processPair(f._1, f._2, language1, language2)) } }
1,892
34.055556
112
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/Tokenizer.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{newReader, newWriter} import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory /** * @author Emmanouil Antonios Platanios */ trait Tokenizer extends FileProcessor { override def process(file: File, language: Language): File = { tokenizeCorpus(file, language) } def tokenizedFile(originalFile: File): File def tokenize(sentence: String, language: Language): String def tokenizeCorpus(file: File, language: Language, bufferSize: Int = 8192): File = { val tokenized = tokenizedFile(file) if (tokenized.notExists) { Tokenizer.logger.info(s"Tokenizing '$file'.") val tokenizedWriter = newWriter(tokenized) newReader(file).lines().toAutoClosedIterator.foreach(sentence => { tokenizedWriter.write(s"${tokenize(sentence, language)}\n") }) tokenizedWriter.flush() tokenizedWriter.close() Tokenizer.logger.info(s"Created tokenized file '$tokenized'.") } tokenized } override def toString: String } object Tokenizer { private[data] val logger = Logger(LoggerFactory.getLogger("Data / Tokenizer")) }
1,888
32.140351
86
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/data/processors/TEDConverter.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.data.processors import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{newReader, newWriter} import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import scala.util.matching.Regex /** * @author Emmanouil Antonios Platanios */ object TEDConverter extends FileProcessor { private val logger = Logger(LoggerFactory.getLogger("Data / TED Converter")) private val ignoredRegex: Regex = """.*(?:<url>|<talkid>|<keywords>|<speaker|<reviewer|<translator).*""".r private val removeRegex : Regex = """(?:<title>|</title>|<doc .*>|</doc>|<description>|</description>)""".r override def process(file: File, language: Language): File = { val textFile = convertedFile(file) if (textFile.notExists) { logger.info(s"Converting TED file '$file' to text file '$textFile'.") val reader = newReader(file) val writer = newWriter(textFile) reader.lines().toAutoClosedIterator.foreach(line => { ignoredRegex.findFirstMatchIn(line) match { case Some(_) => () case None => writer.write(s"${removeRegex.replaceAllIn(line, "")}\n") } }) writer.flush() writer.close() logger.info(s"Converted TED file '$file' to text file '$textFile'.") } textFile } private def convertedFile(originalFile: File): File = { originalFile.sibling("converted." + originalFile.name) } }
2,101
34.627119
109
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/vocabulary/SimpleVocabularyGenerator.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.vocabulary import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{newReader, newWriter} import org.platanios.symphony.mt.utilities.{MutableFile, TrieWordCounter} import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import scala.util.matching.Regex /** Simple vocabulary generator that generates a vocabulary by simply splitting the input text files on spaces. * * @param sizeThreshold Vocabulary size threshold. If non-negative, then the created vocabulary size will be * bounded by this number. This means that only the `sizeThreshold` most frequent words will * be kept. * @param countThreshold Vocabulary count threshold. If non-negative, then all words with counts less than * `countThreshold` will be ignored. * @param replaceExisting If `true`, existing vocabulary files will be replaced, if found. * @param bufferSize Buffer size to use while reading and writing files. * * @author Emmanouil Antonios Platanios */ class SimpleVocabularyGenerator protected ( val sizeThreshold: Int = -1, val countThreshold: Int = -1, val replaceExisting: Boolean = false, val bufferSize: Int = 8192 ) extends VocabularyGenerator { protected val whitespaceRegex: Regex = "\\s+".r /** Returns the vocabulary file name that this generator uses / will use. * * @param languages Languages for which a vocabulary will be generated. * @return Vocabulary file name. */ override def filename(languages: Seq[Language]): String = { val suffix = languages.map(_.abbreviation).sorted.mkString(".") if (sizeThreshold == -1 && countThreshold == -1) s"vocab.$suffix" else if (countThreshold == -1) s"vocab.s$sizeThreshold.$suffix" else if (sizeThreshold == -1) s"vocab.c$countThreshold.$suffix" else s"vocab.s$sizeThreshold.c$countThreshold.$suffix" } /** Generates/Replaces a vocabulary file given a sequence of tokenized text files. * * @param languages Languages for which a merged vocabulary will be generated. * @param tokenizedFiles Tokenized text files to use for generating the vocabulary file. * @param vocabDir Directory in which to save the generated vocabulary files. * @return The generated/replaced vocabulary file. */ override protected def generate( languages: Seq[Language], tokenizedFiles: Seq[MutableFile], vocabDir: File ): File = { val vocabFile = vocabDir / filename(languages) if (replaceExisting || vocabFile.notExists) { SimpleVocabularyGenerator.logger.info(s"Generating vocabulary file for ${languages.mkString(", ")}.") vocabFile.parent.createDirectories() val writer = newWriter(vocabFile) tokenizedFiles.map(_.get).toIterator.flatMap(file => { newReader(file).lines().toAutoClosedIterator .flatMap(whitespaceRegex.split) }).foldLeft(TrieWordCounter())((counter, word) => { counter.insertWord(word.trim) counter }).words(sizeThreshold, countThreshold) .toSeq .sortBy(-_._1) .map(_._2) .distinct .foreach(word => writer.write(word + "\n")) writer.flush() writer.close() SimpleVocabularyGenerator.logger.info(s"Generated vocabulary file for ${languages.mkString(", ")}.") } else { SimpleVocabularyGenerator.logger.info(s"Vocabulary for ${languages.mkString(", ")} already exists: $vocabFile.") } vocabFile } override def toString: String = s"simple-$sizeThreshold-$countThreshold" } object SimpleVocabularyGenerator { private[SimpleVocabularyGenerator] val logger = Logger(LoggerFactory.getLogger("Vocabulary / Simple Generator")) def apply( sizeThreshold: Int = -1, countThreshold: Int = -1, replaceExisting: Boolean = false, bufferSize: Int = 8192 ): SimpleVocabularyGenerator = { new SimpleVocabularyGenerator(sizeThreshold, countThreshold, replaceExisting, bufferSize) } }
4,782
39.533898
118
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/vocabulary/DummyVocabularyGenerator.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.vocabulary import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.newWriter import org.platanios.symphony.mt.utilities.MutableFile import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory /** Dummy vocabulary generator that generates a vocabulary containing numbers starting at `0` and ending at `size - 1`. * * @param size Vocabulary size to use. * @param replaceExisting If `true`, existing vocabulary files will be replaced, if found. * @param bufferSize Buffer size to use while writing vocabulary files. * * @author Emmanouil Antonios Platanios */ class DummyVocabularyGenerator protected ( val size: Int, val replaceExisting: Boolean = false, val bufferSize: Int = 8192 ) extends VocabularyGenerator { /** Returns the vocabulary file name that this generator uses / will use. * * @param languages Languages for which a vocabulary will be generated. * @return Vocabulary file name. */ override def filename(languages: Seq[Language]): String = { s"vocab.dummy.$size.${languages.map(_.abbreviation).sorted.mkString(".")}" } /** Generates/Replaces a vocabulary file given a sequence of tokenized text files. * * @param languages Languages for which a merged vocabulary will be generated. * @param tokenizedFiles Tokenized text files to use for generating the vocabulary file. * @param vocabDir Directory in which to save the generated vocabulary files. * @return The generated/replaced vocabulary file. */ override protected def generate( languages: Seq[Language], tokenizedFiles: Seq[MutableFile], vocabDir: File ): File = { val vocabFile = vocabDir / filename(languages) if (replaceExisting || vocabFile.notExists) { DummyVocabularyGenerator.logger.info(s"Generating vocabulary file for ${languages.mkString(", ")}.") vocabFile.parent.createDirectories() val writer = newWriter(vocabFile) (0 until size).foreach(wordId => writer.write(wordId + "\n")) writer.flush() writer.close() DummyVocabularyGenerator.logger.info(s"Generated vocabulary file for ${languages.mkString(", ")}.") } else { DummyVocabularyGenerator.logger.info(s"Vocabulary for ${languages.mkString(", ")} already exists: $vocabFile.") } vocabFile } override def toString: String = s"dummy-$size" } object DummyVocabularyGenerator { private[DummyVocabularyGenerator] val logger = Logger(LoggerFactory.getLogger("Vocabulary / Dummy Generator")) def apply(size: Int, replaceExisting: Boolean = false, bufferSize: Int = 8192): DummyVocabularyGenerator = { new DummyVocabularyGenerator(size, replaceExisting, bufferSize) } }
3,445
39.541176
119
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/vocabulary/BPEVocabularyGenerator.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.vocabulary import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.data.{newReader, newWriter} import org.platanios.symphony.mt.utilities.{MutableFile, PriorityCounter, TrieWordCounter} import better.files._ import com.twitter.util.LruMap import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory import scala.collection.mutable import scala.collection.parallel.mutable.ParMap import scala.util.matching.Regex /** Uses byte pair encoding (BPE) to learn a variable-length encoding of the vocabulary in a text. * Unlike the original BPE, it does not compress the plain text, but can be used to reduce the vocabulary of a text to * a configurable number of symbols, with only a small increase in the number of tokens. * * '''Reference:''' Rico Sennrich, Barry Haddow and Alexandra Birch (2016). Neural Machine Translation of Rare Words * with Subword Units. Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics * (ACL 2016). Berlin, Germany. * * '''NOTE:''' Our implementation is based upon the one of the original paper authors, which can be found at * [https://github.com/rsennrich/subword-nmt](https://github.com/rsennrich/subword-nmt). * * @param numMergeOps Number of BPE merge operations to learn when generating a new BPE vocabulary. * @param separator Separator symbol appended to all inter-word symbols while encoding sentences. This allows * for decoding BPE-encoded sentences, after a translation is done. * @param glossary * @param caseSensitive * @param countThreshold Symbols pairs which appears less than `countThreshold` times will be ignored. * @param replaceExisting If `true`, existing vocabulary files will be replaced, if found. * @param bufferSize Buffer size to use while reading and writing files. * * @author Emmanouil Antonios Platanios */ class BPEVocabularyGenerator protected ( val numMergeOps: Int = 32000, val separator: String = "@@", val glossary: Set[String] = BPEVocabularyGenerator.DEFAULT_GLOSSARY, val caseSensitive: Boolean = true, val countThreshold: Int = -1, val replaceExisting: Boolean = false, val cacheSize: Int = 10000, val bufferSize: Int = 8192 ) extends VocabularyGenerator { protected val glossaryRegex: Regex = BPEVocabularyGenerator.glossaryRegex(glossary) protected val mergePairs : mutable.Map[Seq[Language], Map[(String, String), Int]] = mutable.Map.empty protected val reversedMergePairs: mutable.Map[Seq[Language], Map[String, (String, String)]] = mutable.Map.empty protected val vocabularies : mutable.Map[Seq[Language], Set[String]] = mutable.Map.empty protected def suffix(languages: Seq[Language]): String = { languages.map(_.abbreviation).sorted.mkString(".") } protected def mergePairsFilename(languages: Seq[Language]): String = { s"merge_pairs.bpe${if (!caseSensitive) ".nc" else ""}.$numMergeOps.${suffix(languages)}" } /** Returns the vocabulary file name that this generator uses / will use. * * @param languages Languages for which a vocabulary will be generated. * @return Vocabulary file name. */ override def filename(languages: Seq[Language]): String = { s"vocab.bpe${if (!caseSensitive) ".nc" else ""}.$numMergeOps.${suffix(languages)}" } /** Generates/Replaces a vocabulary file given a sequence of tokenized text files. * * @param languages Languages for which a merged vocabulary will be generated. * @param tokenizedFiles Tokenized text files to use for generating the vocabulary file. * @param vocabDir Directory in which to save the generated vocabulary files. * @return The generated/replaced vocabulary file. */ override protected def generate( languages: Seq[Language], tokenizedFiles: Seq[MutableFile], vocabDir: File ): File = { if (!mergePairs.contains(languages)) { mergePairs += languages -> Map.empty reversedMergePairs += languages -> Map.empty vocabularies += languages -> Set.empty } // We first generate the merge pairs, if necessary. val mergePairsFile = vocabDir / mergePairsFilename(languages) if (mergePairsFile.exists && !replaceExisting) { BPEVocabularyGenerator.logger.info( s"Loading existing BPE coding for ${languages.mkString(", ")}: $mergePairsFile.") initializeMergePairs(languages, vocabDir) } else { BPEVocabularyGenerator.logger.info(s"Learning BPE coding for ${languages.mkString(", ")}.") mergePairsFile.parent.createDirectories() val mergePairsWriter = newWriter(mergePairsFile) val tokens = mutable.ArrayBuffer(tokenizedFiles.map(_.get).toIterator.flatMap(file => { newReader(file).lines().toAutoClosedIterator .flatMap(BPEVocabularyGenerator.whitespaceRegex.split) }).foldLeft(TrieWordCounter())((counter, word) => { counter.insertWord(word) counter }).words().map(p => (p._1, { val parts = { if (caseSensitive) p._2.toCharArray.map(_.toString) else p._2.toLowerCase().toCharArray.map(_.toString) } parts.update(parts.length - 1, parts.last + BPEVocabularyGenerator.END_OF_WORD_SYMBOL) parts.toSeq })).toSeq: _*) val pairStatistics = BPEVocabularyGenerator.computePairStatistics(tokens) val counts = pairStatistics.counts val indices = pairStatistics.indices var continue = true var currentSymbol = 0 var progressLogTime = System.currentTimeMillis while (currentSymbol < numMergeOps && continue) { val time = System.currentTimeMillis if (time - progressLogTime >= 1e4) { val numBars = Math.floorDiv(10 * currentSymbol, numMergeOps) BPEVocabularyGenerator.logger.info( s"│${"═" * numBars}${" " * (10 - numBars)}│ " + s"%${numMergeOps.toString.length}s / $numMergeOps BPE symbols processed.".format(currentSymbol)) progressLogTime = time } val mostFrequent = if (counts.nonEmpty) counts.dequeueMax() else null if (mostFrequent._1 < countThreshold) { BPEVocabularyGenerator.logger.info( s"No pair has frequency higher than $countThreshold. Stopping the byte pair encoding (BPE) iteration.") continue = false } else { if (!mergePairs(languages).contains(mostFrequent._2)) { mergePairs(languages) += mostFrequent._2 -> currentSymbol reversedMergePairs(languages) += mostFrequent._2._1 + mostFrequent._2._2 -> mostFrequent._2 mergePairsWriter.write(s"${mostFrequent._2._1}\t${mostFrequent._2._2}\n") } // Replace the newly merged pair in the tokens and update the pair statistics. val changes = indices(mostFrequent._2).filter(_._2 >= 1).map(p => { val index = p._1.toInt val (count, word) = tokens(index) val newWord = BPEVocabularyGenerator.replacePair(mostFrequent._2, word, caseSensitive) tokens.update(index, (count, newWord)) BPEVocabularyGenerator.Change(index, word, newWord, count) }) BPEVocabularyGenerator.updatePairStatistics(mostFrequent._2, changes, counts, indices) } currentSymbol += 1 } mergePairsWriter.flush() mergePairsWriter.close() BPEVocabularyGenerator.logger.info( s"│${"═" * 10}│ %${numMergeOps.toString.length}s / $numMergeOps BPE symbols processed.".format(currentSymbol)) BPEVocabularyGenerator.logger.info(s"Learned BPE coding for ${languages.mkString(", ")}: $mergePairsFile.") } // We then generate the vocabulary, if necessary. val vocabFile = vocabDir / filename(languages) val vocabWriter = { if (vocabFile.exists && !replaceExisting) { BPEVocabularyGenerator.logger.info(s"Vocabulary for ${languages.mkString(", ")} already exists: $vocabFile.") initializeVocabularies(languages, vocabDir) None } else { BPEVocabularyGenerator.logger.info(s"Generating vocabulary file for ${languages.mkString(", ")}.") vocabFile.parent.createDirectories() Some(newWriter(vocabFile)) } } // Irrespective of whether a new vocabulary is being generated, or an existing one was loaded, we also convert the // provided tokenized files to their encoded equivalent. tokenizedFiles.foreach(mutableFile => { val oldFile = mutableFile.get val file = oldFile.sibling( s"${oldFile.nameWithoutExtension(includeAll = false)}" + s".bpe${if (!caseSensitive) ".nc" else ""}" + s".$numMergeOps.${languages.map(_.abbreviation).sorted.mkString(".")}" + s".${oldFile.extension(includeDot = false, includeAll = false).get}") mutableFile.set(file) if (replaceExisting || file.notExists) { BPEVocabularyGenerator.logger.info(s"Applying BPE coding to file: $oldFile.") val fileWriter = if (replaceExisting || file.notExists) Some(newWriter(file)) else None val cache = new LruMap[String, Seq[String]](cacheSize) newReader(oldFile).lines().toAutoClosedIterator .filter(_.length > 0) .foreach(line => { var sentence = BPEVocabularyGenerator.whitespaceRegex.split(line) sentence = encodeSentence(languages, sentence, cache).toArray if (sentence.nonEmpty) fileWriter.foreach(_.write(s"${sentence.mkString(" ")}\n")) }) fileWriter.foreach(w => { w.flush() w.close() }) } }) vocabWriter.foreach(writer => { val tokens = tokenizedFiles.toIterator.flatMap(mutableFile => { if (replaceExisting || vocabWriter.isDefined) { newReader(mutableFile.get).lines().toAutoClosedIterator .flatMap(line => BPEVocabularyGenerator.whitespaceRegex.split(line)) } else { Iterator.empty } }) tokens.foldLeft(TrieWordCounter())((counter, word) => { counter.insertWord(word.trim) counter }).words() .toSeq .sortBy(-_._1) .map(_._2) .distinct .foreach(word => { vocabularies(languages) += word writer.write(word + "\n") }) writer.flush() writer.close() BPEVocabularyGenerator.logger.info(s"Generated vocabulary file for ${languages.mkString(", ")}.") }) BPEVocabularyGenerator.logger.info(s"Applied BPE coding to all provided files for ${languages.mkString(", ")}.") vocabFile } /** Initializes the merge pairs of this BPE generators from an existing file. * * @param languages Languages for which a vocabulary has been generated. * @param vocabDir Directory in which the generated vocabulary file and any other relevant files have been saved. */ protected def initializeMergePairs(languages: Seq[Language], vocabDir: File): Unit = { val mergePairsFile = vocabDir / mergePairsFilename(languages) mergePairs += languages -> newReader(mergePairsFile).lines().toAutoClosedIterator .filter(_ != "") .map(l => { val parts = l.split("\t") (parts(0), parts(1)) }).zipWithIndex.toMap reversedMergePairs += languages -> mergePairs(languages).toSeq.map(p => p._1._1 + p._1._2 -> p._1).toMap } /** Initializes the vocabularies of this BPE generators from an existing file. * * @param languages Languages for which a vocabulary has been generated. * @param vocabDir Directory in which the generated vocabulary file and any other relevant files have been saved. */ protected def initializeVocabularies(languages: Seq[Language], vocabDir: File): Unit = { val vocabFile = vocabDir / filename(languages) vocabularies += languages -> newReader(vocabFile).lines().toAutoClosedIterator .filter(_ != "") .toSet } /** Returns a vocabulary for the specified languages, ready to be used by machine translation models. * * @param languages Languages for which to return a vocabulary. * @param vocabDir Directory in which the generated vocabulary file and any other relevant files have been saved. * @return Created vocabulary. */ override protected def getVocabulary(languages: Seq[Language], vocabDir: File): Vocabulary = { CodedVocabulary(vocabDir / filename(languages), s => encodeSentence(languages, s), decodeSentence) } /** Encodes the provided sentence to a sequence of BPE coded words. * * @param languages Languages in which the sentence is written. * @param sentence Sentence to encode as a sequence of words. * @param cache Optional cache of already encoded words, used to speed up the encoding process. * @return Encoded sentence as a sequence of BPE coded words. */ def encodeSentence( languages: Seq[Language], sentence: Seq[String], cache: mutable.Map[String, Seq[String]] = mutable.Map.empty ): Seq[String] = { // TODO: Add support for glossaries (i.e., words that will be encoded with the identity function. sentence.flatMap(word => encodeWord(languages, word, cache)) } /** Encodes the provided word to a sequence of BPE coded words. * * @param languages Languages in which the word is written. * @param word Word to encode. * @param cache Optional cache of already encoded words, used to speed up the encoding process. * @return Encoded word as a sequence of BPE coded words. */ def encodeWord( languages: Seq[Language], word: String, cache: mutable.Map[String, Seq[String]] = mutable.Map.empty ): Seq[String] = { cache.getOrElseUpdate(word, { var wordParts = BPEVocabularyGenerator.splitWithDelimiters(word, glossaryRegex, keepEmpty = false) if (wordParts.length < 2) { wordParts } else { wordParts = wordParts.updated( wordParts.length - 1, wordParts.last + BPEVocabularyGenerator.END_OF_WORD_SYMBOL) var pairs = { if (caseSensitive) wordParts.sliding(2).map(p => (p(0), p(1))).toArray else wordParts.sliding(2).map(p => (p(0).toLowerCase(), p(1).toLowerCase())).toArray } var continue = true while (pairs.nonEmpty && continue) { val pair = pairs.map(p => (p, mergePairs(languages).get(p))).minBy(_._2.getOrElse(Int.MaxValue)) if (pair._2.isEmpty) { continue = false } else { wordParts = BPEVocabularyGenerator.replacePair(pair._1, wordParts, caseSensitive) pairs = { if (wordParts.length < 2) Array.empty else if (caseSensitive) wordParts.sliding(2).map(p => (p(0), p(1))).toArray else wordParts.sliding(2).map(p => (p(0).toLowerCase(), p(1).toLowerCase())).toArray } } } // Remove end-of-word symbols. if (wordParts.last.endsWith(BPEVocabularyGenerator.END_OF_WORD_SYMBOL)) wordParts = wordParts.updated(wordParts.length - 1, wordParts.last .dropRight(BPEVocabularyGenerator.END_OF_WORD_SYMBOL.length)) // Check if the new words parts are in the vocabulary, and backtrack if necessary. wordParts = BPEVocabularyGenerator.checkVocabularyAndSplit( wordParts, reversedMergePairs(languages), vocabularies(languages), separator) wordParts } }) } /** Decodes the provided sentence to a sequence of words (before the BPE encoding was applied). * * @param sentence Sentence to decode as a sequence of BPE coded words. * @return Decoded sentence as a sequence of words. */ def decodeSentence(sentence: Seq[String]): Seq[String] = { val decodedSentence = mutable.ArrayBuffer.empty[String] var i = 0 var j = 0 while (i < sentence.length) { if (j >= decodedSentence.length) decodedSentence += "" if (sentence(i).endsWith(separator)) { decodedSentence(j) += sentence(i).dropRight(separator.length) } else { decodedSentence(j) += sentence(i) j += 1 } i += 1 } decodedSentence } override def toString: String = { if (countThreshold > 0) s"bpe-$numMergeOps-$countThreshold" else s"bpe-$numMergeOps" } } object BPEVocabularyGenerator { private[BPEVocabularyGenerator] val logger = Logger(LoggerFactory.getLogger("Vocabulary / BPE Generator")) def apply( numMergeOps: Int = 32000, separator: String = "@@", glossary: Set[String] = DEFAULT_GLOSSARY, caseSensitive: Boolean = true, countThreshold: Int = -1, replaceExisting: Boolean = false, cacheSize: Int = 10000, bufferSize: Int = 8192 ): BPEVocabularyGenerator = { new BPEVocabularyGenerator( numMergeOps, separator, glossary, caseSensitive, countThreshold, replaceExisting, cacheSize, bufferSize) } /** End-of-word symbol used by the BPE vocabulary generator. */ val END_OF_WORD_SYMBOL: String = "</w>" /** Regular expression used for tokenizing sentences. */ private[BPEVocabularyGenerator] val whitespaceRegex: Regex = "\\s+".r /** Default glossary to use. */ private[BPEVocabularyGenerator] val DEFAULT_GLOSSARY: Set[String] = Set( "e.g", "i.e", "&amp;", "&#124;", "&lt;", "&gt;", "&apos;", "&quot;", "&#91;", "&#93;") private[BPEVocabularyGenerator] def glossaryRegex(glossary: Set[String]): Regex = { val escapedGlossary = glossary.map(java.util.regex.Pattern.quote) s"(?:${escapedGlossary.mkString("|")})|(?!${escapedGlossary.mkString("|")})".r } private[BPEVocabularyGenerator] def splitWithDelimiters( string: String, regex: Regex, keepEmpty: Boolean = false ): Seq[String] = { val parts = mutable.ArrayBuffer.empty[String] parts.sizeHint(string.length) val p = regex.pattern val m = p.matcher(string) var lastEnd = 0 while (m.find) { val start = m.start if (lastEnd != start) parts += string.substring(lastEnd, start) if (keepEmpty || m.group.length > 0) parts += m.group lastEnd = m.end } if (lastEnd != string.length) parts += string.substring(lastEnd) parts } private[BPEVocabularyGenerator] case class PairStatistics( counts: PriorityCounter[(String, String)], indices: ParMap[(String, String), mutable.LongMap[Long]]) private[BPEVocabularyGenerator] case class Change( index: Int, word: Seq[String], newWord: Seq[String], count: Long) private[BPEVocabularyGenerator] def updateIndices( indices: ParMap[(String, String), mutable.LongMap[Long]], pair: (String, String), index: Int, increment: Long ): Unit = { if (!indices.contains(pair)) indices.put(pair, mutable.LongMap.empty[Long]) if (!indices(pair).contains(index)) indices(pair).put(index, increment) else indices(pair).put(index, indices(pair)(index) + increment) } /** Computes the pair statistics for the provided vocabulary of words. * * @param words Vocabulary of words for which to compute statistics (each tuple contains a count and a word). * @return Computed statistics. */ private[BPEVocabularyGenerator] def computePairStatistics( words: Seq[(Long, Seq[String])] ): PairStatistics = { val counts = PriorityCounter[(String, String)]() val indices = ParMap.empty[(String, String), mutable.LongMap[Long]] words.zipWithIndex.filter(_._1._2.length > 1).foreach { case ((count, symbols), index) => symbols.sliding(2).foreach(s => { val pair = (s(0), s(1)) counts.add(pair, count) updateIndices(indices, pair, index, 1) }) } PairStatistics(counts, indices) } /** Replaces all occurrences of the provided symbol pair in `word` with the joined symbol. * * @param pair Symbol pair to replace in `word`. * @param word Word as a sequence of symbols. * @param caseSensitive Boolean indicating whether to be case-sensitive. * @return New word with `pair` replaced in `word`. */ @inline private[BPEVocabularyGenerator] final def replacePair( pair: (String, String), word: Seq[String], caseSensitive: Boolean ): Seq[String] = { val newWord = Array.ofDim[String](word.size) var j = 0 var k = 0 while (j < word.length - 1) { val part1 = if (caseSensitive) word(j) else word(j).toLowerCase() val part2 = if (caseSensitive) word(j + 1) else word(j + 1).toLowerCase() if (part1 == pair._1 && part2 == pair._2) { val joinedPair = word(j) + word(j + 1) newWord(k) = joinedPair k += 1 j += 2 } else { newWord(k) = word(j) k += 1 j += 1 } } if (j == word.length - 1) { newWord(k) = word(j) k += 1 } newWord.take(k) } /** Minimally updates the symbol pair statistics, based on the provided list of changes. * * This method takes advantage of the fact that if we merge a pair of symbols, only pairs that overlap with * occurrences of this pair are affected and need to be updated. * * @param pair Symbol pair that was merged. * @param changes Changes in the vocabulary of words resulting from the merge. * @param counts Symbol pair counts that will be updated. * @param indices Map that will be updated, containing the indices where each symbol pair is found in `words`, * along with their corresponding counts. */ private[BPEVocabularyGenerator] def updatePairStatistics( pair: (String, String), changes: Iterable[Change], counts: PriorityCounter[(String, String)], indices: ParMap[(String, String), mutable.LongMap[Long]] ): Unit = { val joinedPair = pair._1 + pair._2 // TODO: counts -= pair counts.update(pair, 0) indices(pair).clear() changes.foreach(change => { // Find all instances of the pair, and update the corresponding statistics. var i = 0 while (i < change.word.length - 1) { if (change.word(i) == pair._1 && change.word(i + 1) == pair._2) { // Assuming a symbol sequence "A B C", if "B C" is merged, we reduce the frequency of "A B". if (i > 0) { val prevPair = (change.word(i - 1), change.word(i)) counts.add(prevPair, -change.count) updateIndices(indices, prevPair, change.index, -1) } // Assuming a symbol sequence "A B C B", if "B C" is merged, we reduce the frequency of "C B". However, we // skip this if the sequence is "A B C B C", because the frequency of "C B" will have already been reduced // by the previous code block. if (i < change.word.length - 2 && (change.word(i + 2) != pair._1 || i >= change.word.length - 3 || change.word(i + 3) != pair._2)) { val nextPair = (change.word(i + 1), change.word(i + 2)) counts.add(nextPair, -change.count) updateIndices(indices, nextPair, change.index, -1) } i += 2 } else { i += 1 } } // Find all instances of the joined pair, and update the corresponding statistics. i = 0 while (i < change.newWord.length) { if (change.newWord(i) == joinedPair) { // Assuming a symbol sequence "A BC D", if "B C" is merged, we increase the frequency of "A BC". if (i > 0) { val prevPair = (change.newWord(i - 1), change.newWord(i)) counts.add(prevPair, change.count) updateIndices(indices, prevPair, change.index, 1) } // Assuming a symbol sequence "A BC B", if "B C" is merged, we increase the frequency of "BC B". However, we // skip this if the sequence is "A BC BC", because the count of "BC BC" will have already been incremented // by the previous code block. if (i < change.newWord.length - 1 && change.newWord(i + 1) != joinedPair) { val nextPair = (change.newWord(i), change.newWord(i + 1)) counts.add(nextPair, change.count) updateIndices(indices, nextPair, change.index, 1) } } i += 1 } }) } /** Recursively splits `wordPart` into smaller units (by reversing BPE merges) until all units are either in the * provided vocabulary, or cannot be split further. * * @param wordPart Word part that needs to be split. * @param reversedMergePairs Reversed symbol pairs merge map. * @param vocabulary Vocabulary of valid words. * @param separator Separator used to denote where a word is split. * @param isLast Boolean value indicating whether `wordPart` is the last part of the word being split. * @return `wordPart` split segments. */ private[BPEVocabularyGenerator] def splitRecursively( wordPart: String, reversedMergePairs: Map[String, (String, String)], vocabulary: Set[String], separator: String, isLast: Boolean = false ): Seq[String] = { val pair = { if (isLast) { reversedMergePairs.get(wordPart + END_OF_WORD_SYMBOL) .map(p => (p._1, p._2.dropRight(END_OF_WORD_SYMBOL.length))) } else { reversedMergePairs.get(wordPart) } } // TODO: !!! What about the case-insensitive case? pair match { case None => Seq(wordPart) case Some((left, right)) => // We first go through the left parts. val leftParts = { if (vocabulary.contains(left + separator)) Seq(left + separator) else splitRecursively(left, reversedMergePairs, vocabulary, separator, isLast = false) } // We then go through the right parts. val rightParts = { if (isLast && vocabulary.contains(right)) Seq(right) else if (!isLast && vocabulary.contains(right + separator)) Seq(right + separator) else splitRecursively(right, reversedMergePairs, vocabulary, separator, isLast = isLast) } leftParts ++ rightParts } } /** Checks for each part in `wordParts` if it is in the provided vocabulary, and segments out-of-vocabulary parts into * smaller units by reversing BPE merge operations. * * @param wordParts Word parts to check and split if necessary. * @param reversedMergePairs Reversed symbol pairs merge map. * @param vocabulary Vocabulary of valid words. * @param separator Separator used to denote where a word is split. * @return New sequence of word parts that represents the same word and may be longer than the provided one. */ private[BPEVocabularyGenerator] def checkVocabularyAndSplit( wordParts: Seq[String], reversedMergePairs: Map[String, (String, String)], vocabulary: Set[String], separator: String ): Seq[String] = { if (vocabulary.isEmpty) { var parts = wordParts var i = 0 while (i < parts.length - 1) { parts = parts.updated(i, parts(i) + separator) i += 1 } parts } else { wordParts.zipWithIndex.flatMap { case (part, index) if index < wordParts.length - 1 && vocabulary.contains(part + separator) => Seq(part + separator) case (part, index) if index < wordParts.length - 1 => splitRecursively(part, reversedMergePairs, vocabulary, separator, isLast = false) case (part, _) if vocabulary.contains(part) => Seq(part) case (part, _) => splitRecursively(part, reversedMergePairs, vocabulary, separator, isLast = true) } } } }
28,799
40.319943
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/vocabulary/Vocabulary.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.vocabulary import org.platanios.symphony.mt.data.{DataConfig, newReader, newWriter} import org.platanios.tensorflow.api._ import better.files._ import com.typesafe.scalalogging.Logger import org.slf4j.LoggerFactory /** Represents a vocabulary of words. * * @param file File containing the vocabulary, with one word per line. * @param size Size of this vocabulary (i.e., number of words). * * @author Emmanouil Antonios Platanios */ class Vocabulary protected ( val file: File, val size: Int ) { /** Creates a vocabulary hash map (from word string to word ID), from the provided vocabulary file. * * @return Vocabulary hash map. */ lazy val stringToIndexHashMap: Map[String, Long] = { newReader(file).lines() .toAutoClosedIterator .toSeq .zipWithIndex.map(p => (p._1, p._2.toLong)) .toMap .withDefaultValue(Vocabulary.UNKNOWN_TOKEN_ID) } /** Creates a vocabulary hash map (from word ID to word string), from the provided vocabulary file. * * @return Vocabulary hash map. */ lazy val indexToStringHashMap: Map[Long, String] = { newReader(file).lines() .toAutoClosedIterator .toSeq .zipWithIndex .map(p => (p._2.toLong, p._1)) .toMap .withDefaultValue(Vocabulary.UNKNOWN_TOKEN) } /** Creates a vocabulary lookup table (from word string to word ID), from the provided vocabulary file. * * @return Vocabulary lookup table. */ def stringToIndexLookupTable(name: String = "StringToIndexTableFromFile"): tf.HashTable[String, Long] = { Vocabulary.stringToIndexTableFromFile( file.path.toAbsolutePath.toString, defaultValue = Vocabulary.UNKNOWN_TOKEN_ID, name = name) } /** Creates a vocabulary lookup table (from word ID to word string), from the provided vocabulary file. * * @return Vocabulary lookup table. */ def indexToStringLookupTable(name: String = "IndexToStringTableFromFile"): tf.HashTable[Long, String] = { Vocabulary.indexToStringTableFromFile( file.path.toAbsolutePath.toString, defaultValue = Vocabulary.UNKNOWN_TOKEN, name = name) } /** Encodes the provided sequence using this vocabulary. This is typically an identity function. * * This method is useful for coded vocabularies, such as the byte-pair-encoding vocabulary. * * @param sequence Sequence of tokens to encode. * @return Encoded sequence of tokens that may differ in size from the input sequence. */ def encodeSequence(sequence: Seq[String]): Seq[String] = sequence /** Decodes the provided sequence using this vocabulary. This is typically an identity function. * * This method is useful for coded vocabularies, such as the byte-pair-encoding vocabulary. * * @param sequence Sequence of tokens to decode. * @return Decoded sequence of tokens that may differ in size from the input sequence. */ def decodeSequence(sequence: Seq[String]): Seq[String] = sequence override def hashCode(): Int = { val prime = 31 var result = 1 result = prime * result + file.hashCode result = prime * result + size.hashCode result } override def equals(that: Any): Boolean = { that match { case other: Vocabulary => file == other.file && size == other.size case _ => false } } } /** Contains utilities for dealing with vocabularies. */ object Vocabulary { private[this] val logger: Logger = Logger(LoggerFactory.getLogger("Vocabulary")) /* Token representing unknown symbols (i.e., not included in this vocabulary). */ val UNKNOWN_TOKEN: String = "<unk>" /* Token representing the beginning of a sequence. */ val BEGIN_OF_SEQUENCE_TOKEN: String = "<s>" /* Token representing the end of a sequence. */ val END_OF_SEQUENCE_TOKEN: String = "</s>" val UNKNOWN_TOKEN_ID : Int = 0 val BEGIN_OF_SEQUENCE_TOKEN_ID: Int = 1 val END_OF_SEQUENCE_TOKEN_ID : Int = 2 /** Creates a new vocabulary. * * @param file File containing the vocabulary, with one word per line. * @param size Size of this vocabulary (i.e., number of words). * @return Created vocabulary. */ protected def apply(file: File, size: Int): Vocabulary = { new Vocabulary(file, size) } /** Creates a new vocabulary from the provided vocabulary file. * * The method first checks if the specified vocabulary file exists and if it does, it checks that special tokens are * being used correctly. If not, this method can optionally create a new file by prepending the appropriate tokens to * the existing one. * * The special tokens check simply involves checking whether the first three tokens in the vocabulary file match the * specified `unknownToken`, `beginSequenceToken`, and `endSequenceToken` values. * * @param file Vocabulary file to check. * @param checkSpecialTokens Boolean value indicating whether or not to check for the use of special tokens, and * prepend them while creating a new vocabulary file, if the check fails. * @param directory Directory to use when creating the new vocabulary file, in case the special tokens * check fails. Defaults to the current directory in which `file` is located, meaning * that if the special tokens check fails, `file` will be replaced with the appended * vocabulary file. * @param dataConfig Data configuration that includes information about the special tokens. * @return Constructed vocabulary. * @throws IllegalArgumentException If the provided vocabulary file could not be loaded. */ @throws[IllegalArgumentException] def apply( file: File, checkSpecialTokens: Boolean = true, directory: File = null, dataConfig: DataConfig = DataConfig() ): Vocabulary = { val check = Vocabulary.check(file, checkSpecialTokens, directory) check match { case None => throw new IllegalArgumentException(s"Could not load the vocabulary file located at '$file'.") case Some((size, path)) => Vocabulary(path, size) } } /** Checks if the specified vocabulary file exists and if it does, checks that special tokens are being used * correctly. If not, this method can optionally create a new file by prepending the appropriate tokens to the * existing one. * * The special tokens check simply involves checking whether the first three tokens in the vocabulary file match the * specified `unknownToken`, `beginSequenceToken`, and `endSequenceToken` values. * * @param file Vocabulary file to check. * @param checkSpecialTokens Boolean value indicating whether or not to check for the use of special tokens, and * prepend them while creating a new vocabulary file, if the check fails. * @param directory Directory to use when creating the new vocabulary file, in case the special tokens * check fails. Defaults to the current directory in which `file` is located, meaning * that if the special tokens check fails, `file` will be replaced with the appended * vocabulary file. * @return Option containing the number of tokens and the checked vocabulary file, which could be a new file. */ private[vocabulary] def check( file: File, checkSpecialTokens: Boolean = true, directory: File = null ): Option[(Int, File)] = { if (file.notExists) { None } else { logger.info(s"Vocabulary file '$file' exists.") var tokens = newReader(file).lines().toAutoClosedIterator .filter(_ != "") .toSeq if (!checkSpecialTokens) { Some((tokens.size, file)) } else { // Verify that the loaded vocabulary using the right special tokens. // If it does not, use those tokens and generate a new vocabulary file. assert(tokens.lengthCompare(3) >= 0, "The loaded vocabulary must contain at least three tokens.") if (tokens(0) != UNKNOWN_TOKEN || tokens(1) != BEGIN_OF_SEQUENCE_TOKEN || tokens(2) != END_OF_SEQUENCE_TOKEN) { logger.info( s"The first 3 vocabulary tokens [${tokens(0)}, ${tokens(1)}, ${tokens(2)}] " + s"are not equal to [$UNKNOWN_TOKEN, $BEGIN_OF_SEQUENCE_TOKEN, $END_OF_SEQUENCE_TOKEN].") tokens = Seq(UNKNOWN_TOKEN, BEGIN_OF_SEQUENCE_TOKEN, END_OF_SEQUENCE_TOKEN) ++ tokens val newFile = if (directory != null) directory.sibling(file.name) else file val writer = newWriter(newFile) tokens.foreach(token => writer.write(s"$token\n")) writer.flush() writer.close() logger.info(s"Created fixed vocabulary file at '$newFile'.") Some((tokens.size, newFile)) } else { Some((tokens.size, file)) } } } } /** Creates a lookup table that converts string tensors into integer IDs. * * This operation constructs a lookup table to convert tensors of strings into tensors of `INT64` IDs. The mapping * is initialized from a vocabulary file specified in `filename`, where the whole line is the key and the zero-based * line number is the ID. * * The underlying table must be initialized by executing the `tf.tablesInitializer()` op or the op returned by * `table.initialize()`. * * Example usage: * * If we have a vocabulary file `"test.txt"` with the following content: * {{{ * emerson * lake * palmer * }}} * Then, we can use the following code to create a table mapping `"emerson" -> 0`, `"lake" -> 1`, and * `"palmer" -> 2`: * {{{ * val table = tf.stringToIndexTableFromFile("test.txt")) * }}} * * @param filename Filename of the text file to be used for initialization. The path must be accessible * from wherever the graph is initialized (e.g., trainer or evaluation workers). * @param vocabularySize Number of elements in the file, if known. If not known, set to `-1` (the default value). * @param defaultValue Default value to use if a key is missing from the table. * @param name Name for the created table. * @return Created table. */ private[Vocabulary] def stringToIndexTableFromFile( filename: String, vocabularySize: Int = -1, defaultValue: Long = -1L, name: String = "StringToIndexTableFromFile" ): tf.HashTable[String, Long] = { tf.nameScope(name) { tf.nameScope("HashTable") { val sharedName = { if (vocabularySize != -1) s"hash_table_${filename}_${vocabularySize}_${tf.TextFileWholeLine}_${tf.TextFileLineNumber}" else s"hash_table_${filename}_${tf.TextFileWholeLine}_${tf.TextFileLineNumber}" } val initializer = tf.LookupTableTextFileInitializer( filename, STRING, INT64, tf.TextFileWholeLine[String], tf.TextFileLineNumber, vocabularySize = vocabularySize) tf.HashTable(initializer, defaultValue, sharedName = sharedName, name = "Table") } } } /** Creates a lookup table that converts integer ID tensors into strings. * * This operation constructs a lookup table to convert tensors of `INT64` IDs into tensors of strings. The mapping * is initialized from a vocabulary file specified in `filename`, where the zero-based line number is the key and the * whole line is the ID. * * The underlying table must be initialized by executing the `tf.tablesInitializer()` op or the op returned by * `table.initialize()`. * * Example usage: * * If we have a vocabulary file `"test.txt"` with the following content: * {{{ * emerson * lake * palmer * }}} * Then, we can use the following code to create a table mapping `0 -> "emerson"`, `1 -> "lake"`, and * `2 -> "palmer"`: * {{{ * val table = tf.indexToStringTableFromFile("test.txt")) * }}} * * @param filename Filename of the text file to be used for initialization. The path must be accessible * from wherever the graph is initialized (e.g., trainer or evaluation workers). * @param vocabularySize Number of elements in the file, if known. If not known, set to `-1` (the default value). * @param defaultValue Default value to use if a key is missing from the table. * @param name Name for the created table. * @return Created table. */ private[Vocabulary] def indexToStringTableFromFile( filename: String, vocabularySize: Int = -1, defaultValue: String = UNKNOWN_TOKEN, name: String = "IndexToStringTableFromFile" ): tf.HashTable[Long, String] = { tf.nameScope(name) { tf.nameScope("HashTable") { val sharedName = { if (vocabularySize != -1) s"hash_table_${filename}_${vocabularySize}_${tf.TextFileLineNumber}_${tf.TextFileWholeLine}" else s"hash_table_${filename}_${tf.TextFileLineNumber}_${tf.TextFileWholeLine}" } val initializer = tf.LookupTableTextFileInitializer( filename, INT64, STRING, tf.TextFileLineNumber, tf.TextFileWholeLine[String], vocabularySize = vocabularySize) tf.HashTable(initializer, defaultValue, sharedName = sharedName, name = "Table") } } } }
14,307
41.966967
120
scala
symphony-mt
symphony-mt-master/mt/src/main/scala/org/platanios/symphony/mt/vocabulary/VocabularyGenerator.scala
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.platanios.symphony.mt.vocabulary import org.platanios.symphony.mt.Language import org.platanios.symphony.mt.utilities.MutableFile import better.files.File /** Vocabulary generator. * * Given a sequence of tokenized (i.e., words separated by spaces) text files, vocabulary generators can be used to * generate vocabulary files. * * @author Emmanouil Antonios Platanios */ trait VocabularyGenerator { /** Returns the vocabulary filename that this generator uses / will use. * * @param languages Languages for which a vocabulary will be generated. * @return Vocabulary filename. */ def filename(languages: Seq[Language]): String = { s"vocab.${languages.map(_.abbreviation).sorted.mkString(".")}" } /** Generates/Replaces a vocabulary file given a sequence of tokenized text files. * * @param languages Languages for which a merged vocabulary will be generated. * @param tokenizedFiles Tokenized text files to use for generating the vocabulary file. * @param vocabDir Directory in which to save the generated vocabulary files. * @return The generated/replaced vocabulary file. */ protected def generate( languages: Seq[Language], tokenizedFiles: Seq[MutableFile], vocabDir: File ): File /** Generates/Replaces the vocabulary files for multiple languages, given a sequence of tokenized text files per * language. * * @param languages Languages for which a vocabulary will be generated. * @param tokenizedFiles Tokenized text files to use for generating the vocabulary files, for each language * @param vocabDir Directory in which to save the generated vocabulary files. * @param shared If `true`, a single vocabulary will be created and shared for all languages. * @return The generated/replaced vocabulary files. */ final def generate( languages: Seq[Language], tokenizedFiles: Seq[Seq[MutableFile]], vocabDir: File, shared: Boolean = false ): Seq[File] = { if (shared) { val files = tokenizedFiles.flatten val vocabulary = generate(languages, files, vocabDir) languages.map(_ => vocabulary) } else { languages.zip(tokenizedFiles).map(a => { val languages = Seq(a._1) generate(languages, a._2, vocabDir) }) } } /** Returns a vocabulary for the specified languages, ready to be used by machine translation models. * * @param languages Languages for which to return a vocabulary. * @param vocabDir Directory in which the generated vocabulary file and any other relevant files have been saved. * @return Created vocabulary. */ protected def getVocabulary(languages: Seq[Language], vocabDir: File): Vocabulary = { Vocabulary(vocabDir / filename(languages)) } /** Returns vocabularies for the specified languages, ready to be used by machine translation models. * * @param languages Languages for which to return vocabularies. * @param vocabDir Directory in which the generated vocabulary files and any other relevant files have been saved. * @param shared If `true`, a single vocabulary will be created and shared for all languages. * @return Created vocabularies. */ final def getVocabularies( languages: Seq[Language], vocabDir: File, shared: Boolean = false ): Seq[Vocabulary] = { if (shared) { val vocabulary = getVocabulary(languages, vocabDir) languages.map(_ => vocabulary) } else { languages.map(l => getVocabulary(Seq(l), vocabDir)) } } override def toString: String }
4,294
37.348214
119
scala