Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[query] Fix order of aggregate_cols, and make aggregate_cols do a loc… #12753

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion hail/python/hail/matrixtable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2223,7 +2223,7 @@ def aggregate_cols(self, expr, _localize=True) -> Any:
"""
base, _ = self._process_joins(expr)
analyze('MatrixTable.aggregate_cols', expr, self._global_indices, {self._col_axis})
cols_table = ir.MatrixColsTable(base._mir)
cols_table = ir.MatrixColsTable(ir.MatrixMapCols(base._mir, base.col._ir, []))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is it kosher for map cols to drop the key? Shouldn't we need to use a key by for that?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't actually have a MatrixKeyColsBy. MMC does both. We could separate it out, but don't have separate nodes because we (a) don't really care about optimizing around col keys since they're unordered, and (b) since the col key is totally ignored as we lower.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry if I'm being dense, but isn't ordering relevant to aggregation? I'm thinking of hl.agg.collect in particular. I thought it was true that the results came in key-order. If ordering is important, why is it safe to drop the key before ir.TableAggregate?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR makes a semantic change in aggregation order (currently in sort order aka order of cols(), but desired behavior is matrixtable column order (localize_entries order). This is what we agreed in team meeting the week before the IBG workshop, but let's revisit Wednesday to make sure we're still on the same page.

subst_query = ir.subst(expr._ir, {}, {'sa': ir.Ref('row', cols_table.typ.row_type)})

agg_ir = ir.TableAggregate(cols_table, subst_query)
Expand Down
30 changes: 16 additions & 14 deletions hail/src/main/scala/is/hail/expr/ir/LowerMatrixIR.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import is.hail.backend.ExecuteContext
import is.hail.expr.ir.functions.{WrappedMatrixToTableFunction, WrappedMatrixToValueFunction}
import is.hail.expr.ir._
import is.hail.types._
import is.hail.types.virtual.{TArray, TBaseStruct, TDict, TInt32, TInterval, TString, TStruct}
import is.hail.types.virtual.{TArray, TBaseStruct, TDict, TInt32, TInterval, TString, TStruct, Type}
import is.hail.utils._

object LowerMatrixIR {
Expand Down Expand Up @@ -156,14 +156,14 @@ object LowerMatrixIR {
case MatrixFilterCols(child, pred) =>
lower(ctx, child, ab)
.mapGlobals('global.insertFields('newColIdx ->
irRange(0, 'global (colsField).len)
irRange(0, 'global(colsField).len)
.filter('i ~>
(let(sa = 'global (colsField)('i))
(let(sa = 'global(colsField)('i))
in subst(lower(ctx, pred, ab), matrixGlobalSubstEnv(child))))))
.mapRows('row.insertFields(entriesField -> 'global ('newColIdx).map('i ~> 'row (entriesField)('i))))
.mapRows('row.insertFields(entriesField -> 'global('newColIdx).map('i ~> 'row(entriesField)('i))))
.mapGlobals('global
.insertFields(colsField ->
'global ('newColIdx).map('i ~> 'global (colsField)('i)))
'global('newColIdx).map('i ~> 'global(colsField)('i)))
.dropFields('newColIdx))

case MatrixAnnotateRowsTable(child, table, root, product) =>
Expand All @@ -176,9 +176,9 @@ object LowerMatrixIR {
case MatrixChooseCols(child, oldIndices) =>
lower(ctx, child, ab)
.mapGlobals('global.insertFields('newColIdx -> oldIndices.map(I32)))
.mapRows('row.insertFields(entriesField -> 'global ('newColIdx).map('i ~> 'row (entriesField)('i))))
.mapRows('row.insertFields(entriesField -> 'global('newColIdx).map('i ~> 'row(entriesField)('i))))
.mapGlobals('global
.insertFields(colsField -> 'global ('newColIdx).map('i ~> 'global (colsField)('i)))
.insertFields(colsField -> 'global('newColIdx).map('i ~> 'global(colsField)('i)))
.dropFields('newColIdx))

case MatrixAnnotateColsTable(child, table, root) =>
Expand All @@ -191,15 +191,15 @@ object LowerMatrixIR {
.apply('rows)
.arrayStructToDict(table.typ.key)) {
'global.insertFields(colsField ->
'global (colsField).map(col ~> col.insertFields(Symbol(root) -> '__dictfield.invoke("get", table.typ.valueType, colKey))))
'global(colsField).map(col ~> col.insertFields(Symbol(root) -> '__dictfield.invoke("get", table.typ.valueType, colKey))))
})

case MatrixMapGlobals(child, newGlobals) =>
lower(ctx, child, ab)
.mapGlobals(
subst(lower(ctx, newGlobals, ab), BindingEnv(Env[IRProxy](
"global" -> 'global.selectFields(child.typ.globalType.fieldNames: _*))))
.insertFields(colsField -> 'global (colsField)))
.insertFields(colsField -> 'global(colsField)))

case MatrixMapRows(child, newRow) =>
def liftScans(ir: IR): IRProxy = {
Expand Down Expand Up @@ -371,7 +371,7 @@ object LowerMatrixIR {
val valueType = elementType.asInstanceOf[TBaseStruct].types(1)
ToDict(StreamMap(ToStream(Ref(uid, aggIR.typ)), eltUID, Let(valueUID, GetField(Ref(eltUID, elementType), "value"),
MakeTuple.ordered(FastSeq(GetField(Ref(eltUID, elementType), "key"),
aggs.foldLeft[IR](liftedBody) { case (acc, (name, _)) => Let(name, GetField(Ref(valueUID, valueType), name), acc) } )))))
aggs.foldLeft[IR](liftedBody) { case (acc, (name, _)) => Let(name, GetField(Ref(valueUID, valueType), name), acc) })))))

case AggArrayPerElement(a, elementName, indexName, body, knownLength, isScan) =>
val ab = new BoxedArrayBuilder[(String, IR)]
Expand Down Expand Up @@ -478,10 +478,12 @@ object LowerMatrixIR {
}

loweredChild.mapGlobals('global.insertFields(colsField ->
aggOutsideTransformer(scanOutsideTransformer(irRange(0, 'global(colsField).len).map(idxSym ~> let(__cols_array = 'global(colsField), sa = '__cols_array(idxSym)) {
aggInsideTransformer(scanInsideTransformer(b0))
})))
))
aggOutsideTransformer(scanOutsideTransformer(ToArray(StreamZip(
FastIndexedSeq(ToStream(GetField(Ref("global", loweredChild.typ.globalType), colsFieldName)), StreamIota(0, 0)),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the second stream is meant to be 1, 2, 3? Why isn't step = 1?

It seems like the old code never had access to the index, so why bother to include it here at all?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

totally a bug, cause of the test failures. The index is used in aggregations/scans to join the column stream with the agg/scan results.

FastIndexedSeq("sa", idx.name),
aggInsideTransformer(scanInsideTransformer(b0)).apply(Env[Type]("sa" -> mir.typ.colType, idx.name -> TInt32)),
ArrayZipBehavior.AssumeSameLength)
)))))

case MatrixFilterEntries(child, pred) =>
val lc = lower(ctx, child, ab)
Expand Down
26 changes: 12 additions & 14 deletions hail/src/main/scala/is/hail/expr/ir/Simplify.scala
Original file line number Diff line number Diff line change
Expand Up @@ -553,20 +553,18 @@ object Simplify {
TableAggregate(child,
AggLet(uid, newRow, Subst(query, BindingEnv(agg = Some(Env("row" -> Ref(uid, newRow.typ))))), isScan = false))

// NOTE: The below rule should be reintroduced when it is possible to put an ArrayAgg inside a TableAggregate
// case TableAggregate(TableParallelize(rowsAndGlobal, _), query) =>
// rowsAndGlobal match {
// // match because we currently don't optimize MakeStruct through Let, and this is a common pattern
// case MakeStruct(Seq((_, rows), (_, global))) =>
// Let("global", global, ArrayAgg(rows, "row", query))
// case other =>
// val uid = genUID()
// Let(uid,
// rowsAndGlobal,
// Let("global",
// GetField(Ref(uid, rowsAndGlobal.typ), "global"),
// ArrayAgg(GetField(Ref(uid, rowsAndGlobal.typ), "rows"), "row", query)))
// }
case TableAggregate(TableParallelize(rowsAndGlobal, _), query) =>
rowsAndGlobal match {
// match because we currently don't optimize MakeStruct through Let, and this is a common pattern
case MakeStruct(Seq((_, rows), (_, global))) =>
Let("global", global, StreamAgg(ToStream(rows), "row", query))
case _ =>
bindIR(rowsAndGlobal) { struct =>
Let("global",
GetField(struct, "global"),
StreamAgg(ToStream(GetField(struct, "rows")), "row", query))
}
}

case ApplyIR("annotate", _, Seq(s, MakeStruct(fields)), _) =>
InsertFields(s, fields)
Expand Down