Repository navigation
Remove redundant deletion matches - #655
jtmaxwell3 wants to merge 5 commits into
Conversation
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #655 +/- ##
=======================================
Coverage 75.64% 75.65%
=======================================
Files 456 456
Lines 38985 39022 +37
Branches 5435 5439 +4
=======================================
+ Hits 29492 29522 +30
- Misses 8347 8354 +7
Partials 1146 1146 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
| // Test with epenthesis rule. | ||
| Morphophonemic.PhonologicalRules.Clear(); | ||
| CreateDeletionRule("rule1", "a"); | ||
| var rule4 = new RewriteRule { Name = "rule4"}; |
There was a problem hiding this comment.
Major: F3. CI fails the format check on this line: Build on ubuntu-22.04 stops at dotnet csharpier check . with RewriteRuleTests.cs - Was not formatted. The cause is the missing space in { Name = "rule4"}. Run dotnet csharpier format . and push.
Public API: unchanged since the last round ( Findings: F1 addressed; F2 addressed; F3 new. Reviewed at e40e1d2 |
|
Removing redundant deletion matches (#655) drops some analyses the parser finds today With #655's filter, HermitCrab no longer finds some analyses it finds without it. In the smallest case, one deletion rule with an alpha variable becomes unrecoverable, because the gap #655 keeps binds the variable from an optional node rather than from the consonant before the deleted segment. Grammar (case A), two deletion rules applied in this order:
Root
Why: unapplying prE gives Checked two ways: hc built from a recent tree with and without #655's Next: is the extra gap intended to produce these analyses? If it is, could the filter keep both gaps when the rule binds variables in its left context, or when the deleted segment could form a run? A unit test reproducing cases B and A is attached (Repro655Tests.cs). Case B: no variables, both rules left-to-right (4 segments)
Root Unapplying r1 gives The same grammar loses taai-type roots for Case C: a right-to-left rule
Parsing Rows and method
Built with Random grammars: 2 to 4 one-segment deletion rules over {p, t, a, i} with random contexts and modes. The lexicon holds every string of length 1 to 5, and all 340 words of length 1 to 4 were parsed. Seeds 1 to 46 were run; the rest was not run. No analysis was gained with #655 in any grammar. What the filter assumesThe PR description says a deletion match next to an optional node is redundant with the match on the node's other side, provided the rule's context does not match the node. That holds as a set of strings when both gaps re-insert the same segment and analysis is otherwise complete. Here neither holds. A left-context variable binds per gap (case A). With DeletionReapplications 0, analysis restores one copy per gap, so two adjacent copies spell a run of deleted segments that a single copy cannot (cases B and C). Unit test (RewriteRuleTests style). Base f9294f9: 2 passed. Head ca20ebe: 2 failed.Base returned using NUnit.Framework;
using SIL.Machine.Annotations;
using SIL.Machine.FeatureModel;
using SIL.Machine.Matching;
namespace SIL.Machine.Morphology.HermitCrab.PhonologicalRules;
public class Repro655Tests : HermitCrabTestBase
{
// Smallest case: two rules, four segments (t, a, p, i), no variables, no right-to-left rule.
// r0: a -> 0 / t _ V (iterative, left to right)
// r1: p -> 0 / _ i (simultaneous)
// Root taai: r0 deletes both a's (t a a i -> t a i -> t i), r1 does not apply, so the surface is "ti".
// Analysing "ti" unapplies r1 first (t p? i). Without #655, r0 re-inserts a? on both sides of p?
// (t a? p? a? i), which spells t a a i. With #655 the gap after p? is dropped (its left context t fails when
// p? is mandatory), one a? remains, and taai is not found.
[Test]
public void DeletionNextToOptionalNode_KeepsRunOfDeletedSegments()
{
FeatureStruct vowel = FeatureStruct
.New(Language.PhonologicalFeatureSystem)
.Symbol(HCFeatureSystem.Segment)
.Symbol("cons-")
.Value;
var r0 = new RewriteRule
{
Name = "r0",
Lhs = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "a")).Value,
};
r0.Subrules.Add(
new RewriteSubrule
{
LeftEnvironment = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "t")).Value,
RightEnvironment = Pattern<Word, ShapeNode>.New().Annotation(vowel).Value,
}
);
var r1 = new RewriteRule
{
Name = "r1",
ApplicationMode = RewriteApplicationMode.Simultaneous,
Lhs = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "p")).Value,
};
r1.Subrules.Add(
new RewriteSubrule
{
RightEnvironment = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "i")).Value,
}
);
Morphophonemic.PhonologicalRules.Add(r0);
Morphophonemic.PhonologicalRules.Add(r1);
LexEntry root = AddEntry("taai", Pos("N"), Morphophonemic, "taai");
try
{
var morpher = new Morpher(TraceManager, Language, 1);
IEnumerable<string> glosses = Glosses(morpher.ParseWord("ti"));
TestContext.Out.WriteLine("ANALYSES ti: " + string.Join(", ", glosses.OrderBy(g => g)));
Assert.That(glosses, Does.Contain("taai"));
}
finally
{
RemoveEntry(root);
}
}
// Case A: a single deletion, made unrecoverable because the surviving gap binds the variable from an optional node.
// prD: C[a vd] -> 0 / (C) C[a vd] _ i (a consonant agreeing in voicing with the one before it is lost before i)
// prE: g -> 0 / _ i
// Root tapti surfaces as "tapi" through prD alone (t agrees with p). Root tapgi surfaces as "tapi" through prE.
// Analysing "tapi" unapplies prE first: t a p g? i. Without #655, prD re-inserts at the gap after p (voicing bound
// from p, giving t) and after g? (voicing bound from g). With #655 the gap after p is dropped (its right context i
// fails when g? is mandatory, and the gap after g? is not left-redundant), so tapti is not found.
[Test]
public void DeletionNextToOptionalNode_KeepsVariableBindingFromLeftContext()
{
FeatureStruct cons = FeatureStruct
.New(Language.PhonologicalFeatureSystem)
.Symbol(HCFeatureSystem.Segment)
.Symbol("cons+")
.Value;
FeatureStruct alphaCons = FeatureStruct
.New(Language.PhonologicalFeatureSystem)
.Symbol(HCFeatureSystem.Segment)
.Symbol("cons+")
.Feature("vd")
.EqualToVariable("a")
.Value;
var prD = new RewriteRule { Name = "prD", Lhs = Pattern<Word, ShapeNode>.New().Annotation(alphaCons).Value };
prD.Subrules.Add(
new RewriteSubrule
{
LeftEnvironment = Pattern<Word, ShapeNode>.New().Annotation(cons).Optional.Annotation(alphaCons).Value,
RightEnvironment = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "i")).Value,
}
);
var prE = new RewriteRule
{
Name = "prE",
Lhs = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "g")).Value,
};
prE.Subrules.Add(
new RewriteSubrule
{
RightEnvironment = Pattern<Word, ShapeNode>.New().Annotation(Character(Table3, "i")).Value,
}
);
Morphophonemic.PhonologicalRules.Add(prD);
Morphophonemic.PhonologicalRules.Add(prE);
LexEntry tapti = AddEntry("tapti", Pos("N"), Morphophonemic, "tapti");
LexEntry tapgi = AddEntry("tapgi", Pos("N"), Morphophonemic, "tapgi");
try
{
var morpher = new Morpher(TraceManager, Language, 1);
IEnumerable<string> glosses = Glosses(morpher.ParseWord("tapi"));
TestContext.Out.WriteLine("ANALYSES tapi: " + string.Join(", ", glosses.OrderBy(g => g)));
Assert.That(glosses, Does.Contain("tapti").And.Contain("tapgi"));
}
finally
{
RemoveEntry(tapti);
RemoveEntry(tapgi);
}
}
private FeatureStruct Pos(string symbol) => FeatureStruct.New(Language.SyntacticFeatureSystem).Symbol(symbol).Value;
private static IEnumerable<string> Glosses(IEnumerable<Word> words) =>
words.Select(w => string.Join(" ", w.AllomorphsInMorphOrder.Select(a => a.Morpheme.Gloss))).ToList();
private void RemoveEntry(LexEntry entry)
{
Morphophonemic.Entries.Remove(entry);
Entries.Remove(entry.Gloss);
}
} |
|
Thanks for this; the speedup is substantial. We ran #655 (head ca20ebe) against its merge base on 23 real and calibration grammars (two with heavy deletion cascades) and all 155 conformance-suite grammars. Analyses are identical in every case, and the slowest words in the two deletion-heavy grammars are 6x to 12x faster in total time. The filter is not result-preserving in general, though. Two small grammars lose analyses that base finds (Repro655Tests.cs, posted earlier in this thread: base passes, head fails):
A fuzz of 46 small random deletion grammars lost analyses in 7 and never gained one. Could the filter keep both gaps when the rule's left context binds variables or when the deleted segment can form a run? If these analyses are considered spurious, a test pinning that decision would help. A case comparing full analysis sets with and without the filter would also help. |
|
For comparison: PanGloss (the Rust port of HC) is landing an exact filter aimed at the same blowup, sillsdev/PanGloss#585 (design in sillsdev/PanGloss#579). Before searching an affix allomorph it checks cheaply whether the allomorph can match the input at all. Analyses are identical on every finished word across our lists, and Tamil does 4-8x less work. The cost is +6% work on Mbugwe and +1.6% on Swahili, where it rarely rejects anything. Next we will measure a corrected version of this PR's gap filter (keeping both gaps when the left context binds variables or the deleted segment can form a run) on its own and combined with #585, and report the numbers here. |
|
Follow-up on our earlier report: we ported this change to the Rust port (PanGloss) and measured it three ways. Instruction counts are Windows hardware counters, 100 random words per grammar. Grammar names are withheld; "grammar A" is the slow agglutinative grammar from our earlier comment. Exactness. A faithful port reproduces the lost-analysis repro (Repro655Tests.cs, earlier in this thread) and loses analyses on 68 of 300 fuzzed grammars. We tried two corrections:
So in our measurements, making it exact removes the speedup on the grammar that needs it. Speed, faithful port (instructions): grammar A -83% (-90% on its heaviest words); grammar B -61%. On every word that finished in both builds, analyses matched the unmodified build. The losses show up only on fuzzed grammars. What we're doing: we're landing an exact prefilter instead (sillsdev/PanGloss#585, grammar A -69%; heaviest words -82%). If this PR merges, we'll port it at our next Machine pin and stack it on #585. We think the exact route to the remaining gain is enumerating optional runs (#635). |
|
The code behind our results is in sillsdev/PanGloss#589. It's a closed PR, kept only as evidence and never to be merged. What we tried. We implemented this PR's redundant-match filter in PanGloss's deletion un-application (
The PR also includes our earlier one-sided version of the same idea, which we rejected before this PR was opened. Why. On our slowest deletion grammar, un-application re-inserts the deleted segment at every gap, up to 2^N optional copies per gap. That's the blowup this PR targets. We wanted to know whether the change keeps the oracle's analyses, whether a corrected version could, and what it gains on its own and combined with our own exact prefilter. What we found (summarised in our previous comment): the raw and per-rule versions drop analyses against the pinned hc.dll on fuzzed grammars, 68 of 300 and 10 of 300. The grammar-wide version is exact on 1,000 seeds, but it never fires on the grammar that needs it, because that grammar has a deletion rule that can apply in runs. On every real word that finished, all versions gave the same analyses as the unmodified build. Records:
|
This PR removes redundant deletion matches when a phonological deletion rule is unapplied. Redundant deletion matches occur when a deletion rule matches next to an optional node. Since the node is optional, the rule can match on either side of it. If the rule's context doesn't match the node, then one of these matches is redundant.
Each unapplication introduces an optional node, and some matching algorithms are exponential in the number of optional nodes, so eliminating a rule application can make a big difference in how long a word takes to parse. This is especially true if the grammar has a lot of phonological deletion rules, since phonological deletion rules produce optional nodes, and so later phonological deletion rules produce a lot of redundant matches. In the worst case, the number of redundant matches is exponential in the number of deletion rules that the grammar has. See RewriteTests.CascadedDeletionRules for an example. Note that when the left context and the right context don't filter, then there are a lot matches in the output.
This speeds up the slowest words in the Puguli project from minutes to seconds. The slowest word is now less than two seconds on my machine. (The Puguli project has 4763 words if you use Run Tests > Parse All Texts.)
This change is