Skip to content

[array.linalg.qr] added sfqr (short-and-fat) as a counterpart to tsqr… - #3575

Merged
mrocklin merged 11 commits into
dask:masterfrom
convexset:array/linalg/sfqr
Jun 10, 2018
Merged

mrocklin merged 11 commits into
dask:masterfrom
convexset:array/linalg/sfqr

Conversation

@convexset

Copy link
Copy Markdown
Contributor

… (tall-and-skinny) to extend the applicability of qr; most "big data" cases using QR decompositions would probably be either short-and-fat or tall-and-skinny #diversity

  • 3 tests added based on those for tsqr
  • flake8 passed

… (tall-and-skinny) to extend the applicability of qr; most "big data" cases using QR decompositions would probably be either short-and-fat or tall-and-skinny #diversity

@mrocklin mrocklin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nice work! A few nitpicky comments below.

Comment thread dask/array/linalg.py Outdated
len(data.chunks[1]) == 1): # Only one column block
raise ValueError(
"Input must have the following properties:\n"
"[tsqr] Input must have the following properties:\n"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Users can get to this error by calling the da.linalg.qr function, but this term, tsqr, may not be well understood by them.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Will keep a reference to tsqr, but also refer to qr and the relevant case.

    if not (data.ndim == 2 and                    # Is a matrix
            len(data.chunks[1]) == 1):         # Only one column block
        raise ValueError(
            "Input must have the following properties:\n"
            "  1. Have two dimensions\n"
            "  2. Have only one column of blocks\n\n"
            "Note: This function (tsqr) supports QR decomposition in the case of\n"
            "tall-and-skinny matrices (single column chunk/block; see qr)"
        )

Some duplication in qr:

    if len(a.chunks[1]) == 1:
        return tsqr(a, name)
    elif len(a.chunks[0]) == 1:
        return sfqr(a, name)
    else:
        raise NotImplemented(
            "qr currently supports only tall-and-skinny (single column chunk/block; see tsqr)\n"
            "and short-and-fat (single row chunk/block; see sfqr) matrices\n\n"
            "Consider use of the rechunk method. For example,\n\n"
            "x.rechunk({0: -1, 1: 'auto'}) or x.rechunk({0: 'auto', 1: -1})\n\n"
            "which rechunk one shorter axis to a single chunk, while allowing\n"
            "the other axis to automatically grow/shrink appropriately."
        )

... but ok because "pure functions".

Comment thread dask/array/tests/test_linalg.py Outdated

q, r = sfqr(data)
q = np.array(q)
r = np.array(r)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You don't need to explicitly compute q and r here. Instead it's best to leave them as dask arrays and pass those into assert_eq, which will both call compute appropriately and run a number of other checks on the dask objects.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You might also consider testing the following:

q, r = da.linalg.qr(data)
qq, rr = np.linalg.qr(mat)

assert_eq(q, qq)
assert_eq(r, rr)

This would, I think, check a number of concerns directly

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It would also be good to verify that this works under a few chunking situations, notably where there is only one chunk, and when chunks are uneven.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah, I see that you handle exactly the chunking cases that I mention here below.

If it makes sense you might consider using pytest.mark.parameterize to combine a few tests. Here is a naive example that might not be appropriate for your situation.

@pytest.mark.parameterize('chunks', [(10, 10), (10, 7), (10, 40)])
def test_sfqr(chunks):
    mat = ...
    data = da.from_array(mat, chunks=chunks)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I see:

q = np.array(q)
r = np.array(r)

is not necessary. I'll change the existing tsqr tests too.

Comment thread dask/array/linalg.py
" 1. Have two dimensions\n"
" 2. Have only one row of blocks\n"
" 3. Either one column of blocks or chunking dimension on rows is at most that on cols"
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We should possibly avoid using terms like sfqr in user-facing error messages. Users just calling da.linalg.qr might not understand this acronym.

We might also consider moving these informative error messages up to da.linalg.qr

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Will keep a reference to sfqr, but also refer to qr and the relevant case.

    if not ((data.ndim == 2) and  # Is a matrix
            (nr == 1) and         # Has exactly one block row
            ((cr <= cc) or        # Chunking dimension on rows is at least that on cols or...
             (nc == 1)) and       # ... only one block col
            _has_even_chunks(data.chunks[1])  # Has uniform chunking on column dimension
           ):
        raise ValueError(
            "Input must have the following properties:\n"
            "  1. Have two dimensions\n"
            "  2. Have only one row of blocks\n"
            "  3. Either one column of blocks or chunking dimension on rows\n"
            "     is at most that on cols (for the first block, if uneven)\n"
            "  4. Has even chunking on column dimension (e.g.: (5,5,5) or\n"
            "     (4,4,3); the last column is the only one allowed to differ)\n\n"
            "Note: This function (sfqr) supports QR decomposition in the case\n"
            "of short-and-fat matrices (single row chunk/block; see qr)"
        )

Some duplication in qr:

    if len(a.chunks[1]) == 1:
        return tsqr(a, name)
    elif len(a.chunks[0]) == 1:
        return sfqr(a, name)
    else:
        raise NotImplemented(
            "qr currently supports only tall-and-skinny (single column chunk/block; see tsqr)\n"
            "and short-and-fat (single row chunk/block; see sfqr) matrices\n\n"
            "Consider use of the rechunk method. For example,\n\n"
            "x.rechunk({0: -1, 1: 'auto'}) or x.rechunk({0: 'auto', 1: -1})\n\n"
            "which rechunk one shorter axis to a single chunk, while allowing\n"
            "the other axis to automatically grow/shrink appropriately."
        )

... but ok because "pure functions".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

... will get rid of requirement 4 which I added. Will support non-uniform chunking like

(
  (10),
  (15, 8, 7, 5, 5)
)

…3,4)); more informative error messages; tests simplified
@convexset

Copy link
Copy Markdown
Contributor Author

Alright, comments addressed. Also ensured that the method supports non-uniform chunking.

e.g.: for a 5x20 matrix,chunks=((5), (8,4,8)) is fine, but chunks=((5), (4,8,8)) is not.

Thanks for the pointer on parametrize.

mrocklin added 2 commits June 8, 2018 09:11
This uses dask functions reliably throughout the test suite

q, r = tsqr(data)
q = np.array(q)
r = np.array(r)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you for cleaning these up, even though they're unrelated to your work here. I've gone through the test suite and replaced the explicit conversion to numpy arrays with dask array functions. I hope you don't mind that I pushed to your branch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

¯_(ツ)_/¯

@convexset

Copy link
Copy Markdown
Contributor Author

Interestingly, looking at the method for TSQR in the reference, the matrix in question should be REALLY skinny...

For a (km) × n matrix (with k chunks/blocks), a single core would have to do a QR decomposition for a (kn) × n matrix. So m should be a lot bigger than n. I think that is something that should be featured in the documentation for the tall-and-skinny case.

@convexset

convexset commented Jun 8, 2018 •

Copy link
Copy Markdown
Contributor Author

... I guess things can be resolved by rechunking and recursing. But that means a bit of administration to rechunk back to the original vertical chunk-height.

Maybe as "future work", the tsqr method might use the largest chunk of the input as a guide for the largest chunk to accept for a single core compute (and force the matter if nothing more can be done).

It's actually hilarious considering what will be done with a ((1, 1, 1), (n)) matrix.

@convexset

convexset commented Jun 8, 2018 •

Copy link
Copy Markdown
Contributor Author

Just to elaborate on what I mean... (say it's a 100 factor linear regression with 500000 rows)...

tsqr[ ((1000, ..., 1000), (100)) | vchunk_limit=None ]
--> tsqr[ ((1000, ..., 1000), (100)) | vchunk_limit=1000 ]  # vchunk_limit will be
                                                            # the max vertical
                                                            # chunk size and be
                                                            # passed down
--> with 500 ((1000), (100)) blocks (A_a)... do a QR decomposition for each
--> distributes the 500 ((100), (100)) R_a blocks into 50 ((1000), (100)) blocks (A_b)
--> with 50 ((1000), (100)) blocks... do a QR decomposition for each
--> distributes the 50 ((100), (100)) R_b blocks into 5 ((1000), (100)) blocks (A_c)
--> with 5 ((1000), (100)) blocks... do a QR decomposition for each
--> joins the 5 ((100), (100)) R_c blocks into a ((500), (100)) block (A_d)
--> does a single core QR decomposition
--> splits Q_d into 5 ((100), (100)) blocks
--> multiply with the Q_c blocks and split result into 50 ((100), (100)) blocks
--> multiply with the Q_b blocks and split into 500 ((100), (100)) blocks
--> multiply with the Q_a blocks to yield Q
--> Q has 500 ((1000), (100)) blocks, R has one ((100), (100)) block

Or... (say it's a 10 factor linear regression with 2500 rows)...

tsqr[ ((100, ..., 100), (10)) | vchunk_limit=None ]
--> tsqr[ ((100, ..., 100), (10)) | vchunk_limit=100 ]  # vchunk_limit will be
                                                        # the max vertical
                                                        # chunk size and be
                                                        # passed down
--> with 25 ((100), (10)) blocks (A_a)... do a QR decomposition for each
--> distributes the 25 ((10), (10)) R_a blocks into 2 ((100), (10)) blocks &
    one ((50), (10)) block (A_b)
--> with 2 ((100), (10)) blocks and one ((50), (10)) block... do a QR decomposition for each
--> `np.vstack`'s the 3 ((10), (10)) R_b blocks into a ((30), (10)) block (A_c)
--> does a single core QR decomposition
--> splits Q_c into 3 ((10), (10)) blocks
--> multiply with the Q_b blocks and split into 25 ((10), (10)) blocks
--> multiply with the Q_a blocks to yield Q
--> Q has 25 ((100), (10)) blocks, R has one ((10), (10)) block

Comment thread dask/array/linalg.py
"x.rechunk({0: -1, 1: 'auto'}) or x.rechunk({0: 'auto', 1: -1})\n\n"
"which rechunk one shorter axis to a single chunk, while allowing\n"
"the other axis to automatically grow/shrink appropriately."
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I suspect that you wanted NotImplementedError here.

In [1]: import dask.array as da

In [2]: x = da.ones((100, 100), chunks=(10, 10))

In [3]: da.linalg.qr(x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-a349040cfc1e> in <module>()
----> 1 da.linalg.qr(x)

~/workspace/dask/dask/array/linalg.py in qr(a, name)
    432     else:
    433         raise NotImplemented(
--> 434             "qr currently supports only tall-and-skinny (single column chunk/block; see tsqr)\n"
    435             "and short-and-fat (single row chunk/block; see sfqr) matrices\n\n"
    436             "Consider use of the rechunk method. For example,\n\n"

TypeError: 'NotImplementedType' object is not callable

We should probably add a test for this to makes sure that this works properly.

I think that we should keep the function names tsqr and sfqr hidden from top-level users if possible. Even though they're pretty clear to those who have some experience with blocked linear algebra they might not be broadly understood among all users.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Should be a NotImplementedError... I'll edit that.

@mrocklin

mrocklin commented Jun 8, 2018

Copy link
Copy Markdown
Member

@convexset I recommend raising the tsqr comments in a separate issue so that that conversation can continue after this PR is closed.

@mrocklin

mrocklin commented Jun 8, 2018

Copy link
Copy Markdown
Member

Other than the NotImplemented issue noted above things here look good to me.

@convexset

Copy link
Copy Markdown
Contributor Author

Have fixed the NotImplementedError thing.

Also noticed when cleaning up tests for tsqr that there is an bug with shape reporting.

#3583

Will comment out test cases for that and then fix it later.

@convexset

Copy link
Copy Markdown
Contributor Author

Fix done. And tests for qr/tsqr/sfqr.

Comment thread dask/array/linalg.py
shape=q_shape, chunks=q_chunks, dtype=qq.dtype)
r = Array(dsk, name_r_st2,
shape=(n, n), chunks=(n, n), dtype=rr.dtype)
shape=r_shape, chunks=n, dtype=rr.dtype)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this change tested anywhere?

Alternatively, could this change be moved into a separate PR? It makes it harder to merge the sfqr changes (which seem good to go) when they become attached to new changes that also need review.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

They are exercised in the new tests.

In fact, it fixes the bug reported in: #3583

a = np.random.random((3, 5))
data = da.from_array(a, chunks=5)
q, r = da.linalg.tsqr(data)
q.shape, r.shape

we get...

((3, 5), (5, 5))

@convexset convexset Jun 10, 2018 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

q.compute() # yields a 3x3 matrix
r.compute() # yields a 3x5 matrix

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah, I missed that. Which test? Or is it in the parametrized tests?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, but let me go make sure that the shapes are explicitly checked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Just added some explicit tests.

Comment thread dask/array/linalg.py

# if len(a.chunks[1]) == 1 and a.shape[0] >= a.shape[1]:
if len(a.chunks[1]) == 1: # and a.shape[0] >= a.shape[1]:
if len(a.chunks[1]) == 1 and len(a.chunks[0]) > 1:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this always the right choice?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes. In the one block case, tsqr does too much work (two decompositions). sfqr is more economical with exactly one.

@mrocklin

Copy link
Copy Markdown
Member

OK, this looks good to me. Merging.

Thanks for doing this @convexset ! Quite a nice contribution, and especially impressive that it's your first PR. Hopefully this is the first of many ;)

@mrocklin
mrocklin merged commit 1a76ba3 into dask:master Jun 10, 2018
@convexset
convexset deleted the array/linalg/sfqr branch June 11, 2018 02:34
convexset added a commit to convexset/dask that referenced this pull request Jun 12, 2018
* master:
  [array.linalg.qr] added sfqr (short-and-fat) as a counterpart to tsqr… (dask#3575)
  Drop Dask Array's `learn` module (dask#3580)
  Adds `isneginf` and `isposinf` (dask#3581)
  Update sizeof definitions (dask#3582)
  BUG: do not raise IndexError for identity slice in array.vindex (dask#3559)
  Correct internal dimension of Dask's SVD (dask#3517)
  Fix check in configuration with env=None (dask#3562)
  Dataframe sample method docstring fix (dask#3566)
  Include "region" in key names for da.store (dask#3540)

# Conflicts:
#	dask/array/linalg.py
#	dask/array/tests/test_linalg.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants