提交 77b87e95 authored 作者: Brandon T. Willard's avatar Brandon T. Willard 提交者: Brandon T. Willard

Move function related modules to their own sub-package in theano.compile.function

上级 9fcb536e
......@@ -106,7 +106,7 @@ Reference
.. function:: function(inputs, outputs, mode=None, updates=None, givens=None, no_default_updates=False, accept_inplace=False, name=None, rebuild_strict=True, allow_input_downcast=None, profile=None, on_unused_input='raise')
Return a :class:`callable object <theano.compile.function_module.Function>` that will calculate `outputs` from `inputs`.
Return a :class:`callable object <theano.compile.function.types.Function>` that will calculate `outputs` from `inputs`.
:type params: list of either Variable or In instances, but not shared
variables.
......@@ -174,7 +174,7 @@ Reference
list is not used in the graph. Possible values are 'raise',
'warn', and 'ignore'.
:rtype: :class:`Function <theano.compile.function_module.Function>`
:rtype: :class:`Function <theano.compile.function.types.Function>`
instance
:returns: a callable object that will compute the outputs (given the inputs)
......@@ -214,5 +214,5 @@ Reference
.. autofunction:: theano.compile.function.function_dump
.. autoclass:: theano.compile.function_module.Function
.. autoclass:: theano.compile.function.types.Function
:members: free, copy, __call__
......@@ -723,10 +723,10 @@ Backtrace when the node is created:
Traceback (most recent call last):
File "test.py", line 9, in <module>
f(np.ones((2,)), np.ones((3,)))
File "/u/bastienf/repos/theano/compile/function_module.py",
File "/u/bastienf/repos/theano/compile/function/types.py",
line 589, in __call__
self.fn.thunks[self.fn.position_of_error])
File "/u/bastienf/repos/theano/compile/function_module.py",
File "/u/bastienf/repos/theano/compile/function/types.py",
line 579, in __call__
outputs = self.fn()
......
......@@ -11,7 +11,7 @@ Random Numbers
== Requirements ==
Theano functions sometimes need random numbers.
Theano functions sometimes need random numbers.
Random operations are not as simple as other operations such as ones_like, or pow(), because the output must be different when we call the same function repeatedly. CompileFunction's new default-valued, updatable input variables make this possible. At the same time we need random streams to be repeatable, and easy to work with. So the basic requirements of our random number mechanism are:
1. Internal random number generators must be used in a clear manner, and be accessible to the caller after a function has been compiled.
......@@ -41,10 +41,13 @@ So the proposal is to provide the missing functionality (the last three requirem
#!python
# create a random generator, providing a default seed to condition how RandomOp instances are produced.
from theano.compile.function import function
r = MetaRandom(metaseed=872364)
# create a different random generator
rr = MetaRandom(metaseed=99)
rr = MetaRandom(metaseed=99)
# create an Op to produce a stream of random numbers.
# This generates random numbers uniformly between 0.0 and 1.0 excluded
......@@ -63,7 +66,7 @@ So the proposal is to provide the missing functionality (the last three requirem
# note: un-named state inputs will be added automatically.
# note: it is not necessary to draw samples for u, even though
# u was created by r before v.
fn_v = compile.function([], [v])
fn_v = function([], [v])
# this prints some representation of v's rng in fn_v.
# The .rng property works for Result instances produced by MetaRandom.
......@@ -72,7 +75,7 @@ So the proposal is to provide the missing functionality (the last three requirem
# compile a function to draw each of u, v, w
# note: un-named state inputs will be added automatically
# note: This function (especially its internal state) is independent from fn_v.
fn_uvw = compile.function([], [u,v,w])
fn_uvw = function([], [u,v,w])
# N.B. The random number streams of fn_v and fn_uvw are independent.
assert fn_v.state[v.rng] != fn_uvw.state[v.rng]
......@@ -110,7 +113,7 @@ The typical case is that only one (global) {{{MetaRandom}}} object is used to pr
class MetaRandom(obj):
def __init__(self, metaseed=<N>): ... # new functions will be initialized so that seed(fn, <N>) has no effect on output.
def __contains__(self, Result): ... # True if Result was returned by a call to self.<distribution>
def results(self): ... # Iterate over returned Result instances in creation order.
......@@ -118,7 +121,7 @@ The typical case is that only one (global) {{{MetaRandom}}} object is used to pr
def getstate(self, fn): ... # See below.
def setstate(self, fn, state): ... # See below.
def uniform(...): ... # return a Result of an Apply of a RandomOp.
def uniform(...): ... # return a Result of an Apply of a RandomOp.
# The return value is also stored internally for __contains__ and results().
def normal(...): ...
def bernoulli(...): ...
......@@ -183,6 +186,9 @@ then any time afterward both {{{r.setstate(fn, state_99)}}} and {{{r.seed(fn, 99
#!python
# create a random state
from theano.compile.function import function
r = RandomState(name = 'r')
# create a different random state
......@@ -204,14 +210,14 @@ then any time afterward both {{{r.setstate(fn, state_99)}}} and {{{r.seed(fn, 99
# compile a function to draw random numbers
# note: it is not necessary to draw samples for u.
# we provide the seed for the RandomState r in the inputs list as a "Type 4" input
fn_v = compile.function([(r, 872364)], [v])
fn_v = function([(r, 872364)], [v])
# compile a function to draw each of u, v, w
# we provide the seeds for the RandomStates r and rr in the inputs list as "Type 4" inputs
# note: the random state for r here is seeded independently from the one in fn_v, which means
# random number generation of fn_v and fn_uvw will not interfere. Since the seed is the
# same, it means they will produce the same sequence of tensors for the output v.
fn_uvw = compile.function([(r, 872364), (rr, 99)], [u,v,w])
fn_uvw = function([(r, 872364), (rr, 99)], [u,v,w])
fn_v() # returns random numbers A
......@@ -228,7 +234,7 @@ then any time afterward both {{{r.setstate(fn, state_99)}}} and {{{r.seed(fn, 99
fn() # returns random numbers A
### Is this state well-defined?
### Is this state well-defined?
### Does there even exist a number such that fn_v.r = N would have no effect on the rng states?
print fn_v.r
......
......@@ -158,4 +158,4 @@ How to reuse (overwrite) a storage tensor
=========================================
``theano.compile.io.Out(gw1, borrow = True)`` for that value in
``compile.function``
``theano.compile.function.function``
......@@ -140,9 +140,9 @@ Running the above code generates the following error message:
Traceback (most recent call last):
File "test1.py", line 31, in <module>
f(numpy.random.rand(5, 10))
File "PATH_TO_THEANO/theano/compile/function_module.py", line 605, in __call__
File "PATH_TO_THEANO/theano/compile/function/types.py", line 605, in __call__
self.fn.thunks[self.fn.position_of_error])
File "PATH_TO_THEANO/theano/compile/function_module.py", line 595, in __call__
File "PATH_TO_THEANO/theano/compile/function/types.py", line 595, in __call__
outputs = self.fn()
ValueError: Shape mismatch: x has 10 cols (and 5 rows) but y has 20 rows (and 10 cols)
Apply node that caused the error: Dot22(x, DimShuffle{1,0}.0)
......@@ -527,7 +527,7 @@ illustrative purposes. As the matrices can't be multiplied element-wise
File "ex.py", line 14, in <module>
f(mat1, mat2)
File "/u/username/Theano/theano/compile/function_module.py", line 451, in __call__
File "/u/username/Theano/theano/compile/function/types.py", line 451, in __call__
File "/u/username/Theano/theano/gof/link.py", line 271, in streamline_default_f
File "/u/username/Theano/theano/gof/link.py", line 267, in streamline_default_f
File "/u/username/Theano/theano/gof/cc.py", line 1049, in execute ValueError: ('Input dimension mis-match. (input[0].shape[0] = 3, input[1].shape[0] = 5)', Elemwise{mul,no_inplace}(a, b), Elemwise{mul,no_inplace}(a, b))
......
......@@ -286,7 +286,7 @@ Copying functions
=================
Theano functions can be copied, which can be useful for creating similar
functions but with different shared variables or updates. This is done using
the :func:`copy()<theano.compile.function_module.Function.copy>` method of ``function`` objects. The optimized graph of the original function is copied,
the :func:`copy()<theano.compile.function.types.Function.copy>` method of ``function`` objects. The optimized graph of the original function is copied,
so compilation only needs to be performed once.
Let's start from the accumulator defined above:
......
import os
import pickle
import re
import shutil
import tempfile
......@@ -7,28 +8,38 @@ import numpy as np
import pytest
import theano
from theano import tensor
from theano.compile.function import function, function_dump
from theano.compile.io import In
def test_function_dump():
v = theano.tensor.vector()
fct1 = theano.function([v], v + 1)
fct1 = function([v], v + 1)
try:
tmpdir = tempfile.mkdtemp()
fname = os.path.join(tmpdir, "test_function_dump.pkl")
theano.function_dump(fname, [v], v + 1)
function_dump(fname, [v], v + 1)
with open(fname, "rb") as f:
l = pickle.load(f)
finally:
if tmpdir is not None:
shutil.rmtree(tmpdir)
fct2 = theano.function(**l)
fct2 = function(**l)
x = [1, 2, 3]
assert np.allclose(fct1(x), fct2(x))
def test_function_name():
x = tensor.vector("x")
func = function([x], x + 1.0)
regex = re.compile(os.path.basename(".*test_function.pyc?"))
assert regex.match(func.name) is not None
class TestFunctionIn:
def test_in_strict(self):
......@@ -36,13 +47,13 @@ class TestFunctionIn:
b = theano.shared(7)
out = a + b
f = theano.function([In(a, strict=False)], out)
f = function([In(a, strict=False)], out)
# works, rand generates float64 by default
f(np.random.rand(8))
# works, casting is allowed
f(np.array([1, 2, 3, 4], dtype="int32"))
f = theano.function([In(a, strict=True)], out)
f = function([In(a, strict=True)], out)
try:
# fails, f expects float64
f(np.array([1, 2, 3, 4], dtype="int32"))
......@@ -54,7 +65,7 @@ class TestFunctionIn:
# on the fact that shared variables cannot be explicit inputs
a = theano.shared(1.0)
with pytest.raises(TypeError):
theano.function([a], a + 1)
function([a], a + 1)
def test_in_shared_variable(self):
# Ensure that an error is raised if the In wrapped is used to wrap
......@@ -62,21 +73,21 @@ class TestFunctionIn:
a = theano.shared(1.0)
a_wrapped = In(a, update=a + 1)
with pytest.raises(TypeError):
theano.function([a_wrapped])
function([a_wrapped])
def test_in_mutable(self):
a = theano.tensor.dvector()
a_out = a * 2 # assuming the op which makes this "in place" triggers
# using mutable=True will let f change the value in aval
f = theano.function([In(a, mutable=True)], a_out, mode="FAST_RUN")
f = function([In(a, mutable=True)], a_out, mode="FAST_RUN")
aval = np.random.rand(10)
aval2 = aval.copy()
assert np.all(f(aval) == (aval2 * 2))
assert not np.all(aval == aval2)
# using mutable=False should leave the input untouched
f = theano.function([In(a, mutable=False)], a_out, mode="FAST_RUN")
f = function([In(a, mutable=False)], a_out, mode="FAST_RUN")
aval = np.random.rand(10)
aval2 = aval.copy()
assert np.all(f(aval) == (aval2 * 2))
......@@ -84,7 +95,7 @@ class TestFunctionIn:
def test_in_update(self):
a = theano.tensor.dscalar("a")
f = theano.function([In(a, value=0.0, update=a + 1)], a, mode="FAST_RUN")
f = function([In(a, value=0.0, update=a + 1)], a, mode="FAST_RUN")
# Ensure that, through the executions of the function, the state of the
# input is persistent and is updated as it should
......@@ -106,7 +117,7 @@ class TestFunctionIn:
shared_var = theano.shared(1.0)
a = theano.tensor.dscalar("a")
a_wrapped = In(a, value=0.0, update=shared_var)
f = theano.function([a_wrapped], [], updates={shared_var: a}, mode="FAST_RUN")
f = function([a_wrapped], [], updates={shared_var: a}, mode="FAST_RUN")
# Ensure that, through the executions of the function, the state of
# the input and the shared variable are appropriate (after N execution,
......@@ -120,7 +131,7 @@ class TestFunctionIn:
a = theano.tensor.wvector("a") # int16
b = theano.tensor.bvector("b") # int8
c = theano.tensor.bscalar("c") # int8
f = theano.function(
f = function(
[
In(a, allow_downcast=True),
In(b, allow_downcast=False),
......@@ -155,7 +166,7 @@ class TestFunctionIn:
b = theano.tensor.fscalar("b")
c = theano.tensor.fscalar("c")
f = theano.function(
f = function(
[
In(a, allow_downcast=True),
In(b, allow_downcast=False),
......@@ -186,7 +197,7 @@ class TestFunctionIn:
b = theano.tensor.fvector("b")
c = theano.tensor.fvector("c")
f = theano.function(
f = function(
[
In(a, allow_downcast=True),
In(b, allow_downcast=False),
......
......@@ -2,8 +2,10 @@ import numpy as np
import pytest
import theano
from theano import tensor
from theano.compile import In, config, pfunc, shared
from theano import config, tensor
from theano.compile.function import pfunc
from theano.compile.io import In
from theano.compile.sharedvalue import shared
from theano.tensor import dmatrices, dmatrix, iscalar, lscalar
......
......@@ -9,7 +9,8 @@ import theano
import theano.gpuarray
import theano.tensor as tt
from theano import config, gof
from theano.compile import UnusedInputError, function
from theano.compile.function import function
from theano.compile.function.types import UnusedInputError
from theano.compile.io import In, Out
from theano.gof import MissingInputError
from theano.utils import exc_message
......
......@@ -7,8 +7,8 @@ import theano
import theano.tensor as tt
from tests import unittest_tools
from theano import config, shared
from theano.compile import function
from theano.compile.builders import OpFromGraph
from theano.compile.function import function
from theano.gof.null_type import NullType
from theano.gradient import DisconnectedType
from theano.tensor.shared_randomstreams import RandomStreams
......
import os
import re
import theano
from theano import tensor
class FunctionName:
def test_function_name(self):
x = tensor.vector("x")
func = theano.function([x], x + 1.0)
regex = re.compile(os.path.basename(".*test_function_name.pyc?:14"))
assert regex.match(func.name) is not None
import numpy as np
from theano import tensor
from theano.compile.pfunc import pfunc
from theano.compile.function.pfunc import pfunc
from theano.compile.sharedvalue import shared
from theano.tensor.nnet import sigmoid
......
......@@ -6,7 +6,7 @@ are rarely used by themselves, instead they are the basis for Tensor Ops
to use numpy's scalar routines.
If you do want to rewrite these tests, bear in mind:
* You don't need to use Composite.
* FunctionGraph and DualLinker are old, use compile.function instead.
* FunctionGraph and DualLinker are old, use theano.compile.function.function instead.
"""
import numpy as np
import pytest
......
......@@ -14,7 +14,7 @@ import theano.sandbox.rng_mrg
import theano.scalar.sharedvar
from tests import unittest_tools as utt
from theano import tensor
from theano.compile.pfunc import rebuild_collect_shared
from theano.compile.function.pfunc import rebuild_collect_shared
from theano.scan_module.scan_op import Scan
......@@ -1077,7 +1077,7 @@ class TestScan:
# Traceback (most recent call last):
# File "/u/bastienf/repos/Theano/tests/test_scan.py", line 434, in test_shared_arguments_with_updates
# theano_y0,theano_y1,theano_y2 = f10(vu2, vy0)
# File "/u/bastienf/repos/theano/compile/function_module.py", line 480, in __call__
# File "/u/bastienf/repos/theano/compile/function/types.py", line 480, in __call__
# self.fn()
# File "/u/bastienf/repos/theano/compile/profilemode.py", line 59, in profile_f
# raise_with_op(node)
......@@ -1089,7 +1089,7 @@ class TestScan:
# inplace_map)
# File "/u/bastienf/repos/theano/scan.py", line 1054, in scan
# something = fn(*fn_args)
# File "/u/bastienf/repos/theano/compile/function_module.py", line 458, in __call__
# File "/u/bastienf/repos/theano/compile/function/types.py", line 458, in __call__
# s.storage[0] = s.type.filter(arg, strict=s.strict)
# File "/u/bastienf/repos/theano/tensor/basic.py", line 415, in filter
# data = theano._asarray(data, dtype = self.dtype) #TODO - consider to pad shape with ones
......
import time
import pytest
sp = pytest.importorskip("scipy", minversion="0.7.0")
from itertools import product
import numpy as np
import pytest
from packaging import version
import theano
from tests import unittest_tools as utt
from tests.tensor.test_sharedvar import makeSharedTester
from theano import compile, config, gof, sparse, tensor
from theano import config, gof, sparse, tensor
from theano.compile.function import function
from theano.gradient import GradientError
from theano.sparse import (
CSC,
CSM,
......@@ -85,6 +82,9 @@ from theano.sparse.basic import (
from theano.sparse.opt import CSMGradC, StructuredDotCSC, UsmmCscDense
sp = pytest.importorskip("scipy", minversion="0.7.0")
# Probability distributions are currently tested in test_sp2.py
# from theano.sparse import (
# Poisson, poisson, Binomial, Multinomial, multinomial)
......@@ -100,7 +100,7 @@ def as_sparse_format(data, format):
def eval_outputs(outputs):
return compile.function([], outputs)()[0]
return function([], outputs)()[0]
# scipy 0.17 will return sparse values in all cases while previous
......@@ -308,9 +308,6 @@ def verify_grad_sparse(op, pt, structured=False, *args, **kwargs):
return utt.verify_grad(conv_op, dpt, *args, **kwargs)
verify_grad_sparse.E_grad = utt.verify_grad.E_grad
class TestVerifyGradSparse:
class FailOp(gof.op.Op):
def __init__(self, structured):
......@@ -345,13 +342,13 @@ class TestVerifyGradSparse:
return [shapes[0]]
def test_grad_fail(self):
with pytest.raises(verify_grad_sparse.E_grad):
with pytest.raises(GradientError):
verify_grad_sparse(
self.FailOp(structured=False),
[sp.sparse.csr_matrix(random_lil((10, 40), config.floatX, 3))],
)
with pytest.raises(verify_grad_sparse.E_grad):
with pytest.raises(GradientError):
verify_grad_sparse(
self.FailOp(structured=True),
[sp.sparse.csr_matrix(random_lil((10, 40), config.floatX, 3))],
......
......@@ -3,6 +3,7 @@ import pytest
import theano
from tests import unittest_tools as utt
from theano.gradient import GradientError
from theano.tensor import (
cast,
complex,
......@@ -78,7 +79,7 @@ class TestRealImag:
aval = np.asarray(rng.randn(2, 5))
try:
utt.verify_grad(f, [aval])
except utt.verify_grad.E_grad as e:
except GradientError as e:
print(e.num_grad.gf)
print(e.analytic_grad)
raise
......@@ -93,7 +94,7 @@ class TestRealImag:
aval = np.asarray(rng.randn(2, 5))
try:
utt.verify_grad(f, [aval])
except utt.verify_grad.E_grad as e:
except GradientError as e:
print(e.num_grad.gf)
print(e.analytic_grad)
raise
......@@ -109,7 +110,7 @@ class TestRealImag:
bval = rng.randn(5)
try:
utt.verify_grad(f, [aval, bval])
except utt.verify_grad.E_grad as e:
except GradientError as e:
print(e.num_grad.gf)
print(e.analytic_grad)
raise
......
......@@ -65,9 +65,7 @@ def test_gc_never_pickles_temporaries():
assert a(g) == a(g) # some sanity checks on the pickling mechanism
def b(fn):
return len(
pickle.dumps(theano.compile.function_module._pickle_Function(fn))
)
return len(pickle.dumps(theano.compile.function.types._pickle_Function(fn)))
assert b(f) == b(f) # some sanity checks on the pickling mechanism
......
差异被折叠。
......@@ -424,7 +424,7 @@ def makeSharedTester(
topo_cst = shape_constant_fct.maker.fgraph.toposort()
if theano.config.mode != "FAST_COMPILE":
assert len(topo_cst) == 1
topo_cst[0].op == theano.compile.function_module.deep_copy_op
topo_cst[0].op == theano.compile.function.types.deep_copy_op
# Test that we can take the grad.
if theano.sparse.enable_sparse and isinstance(
......
......@@ -4,8 +4,8 @@ When a compiled theano has shared vars, their values are also being pickled.
Side notes useful for debugging:
The pickling tools theano uses is here:
theano.compile.function_module._pickle_Function()
theano.compile.function_module._pickle_FunctionMaker()
theano.compile.function.types._pickle_Function()
theano.compile.function.types._pickle_FunctionMaker()
Whether reoptimize the pickled function graph is handled by
FunctionMaker.__init__()
The config option is in configdefaults.py
......
......@@ -77,19 +77,6 @@ def verify_grad(op, pt, n_tests=2, rng=None, *args, **kwargs):
tt.verify_grad(op, pt, n_tests, rng, *args, **kwargs)
#
# This supports the following syntax:
#
# try:
# verify_grad(...)
# except verify_grad.E_grad, e:
# print e.num_grad.gf
# print e.analytic_grad
# raise
#
verify_grad.E_grad = tt.verify_grad.E_grad
# A helpful class to check random values close to the boundaries
# when designing new tests
class MockRandomState:
......
......@@ -77,7 +77,6 @@ __api_version__ = 1
from theano import scalar, tensor
from theano.compile import (
FunctionMaker,
In,
Mode,
OpFromGraph,
......@@ -87,13 +86,13 @@ from theano.compile import (
SymbolicInput,
SymbolicOutput,
as_op,
function,
function_dump,
predefined_linkers,
predefined_modes,
predefined_optimizers,
shared,
)
from theano.compile.function import function, function_dump
from theano.compile.function.types import FunctionMaker
from theano.gof import (
Apply,
CLinker,
......
from theano.compile.builders import *
from theano.compile.builders import OpFromGraph, ops_with_inner_function
from theano.compile.debugmode import DebugMode
from theano.compile.function import function, function_dump
from theano.compile.function_module import *
from theano.compile.io import *
from theano.compile.mode import *
from theano.compile.function.pfunc import Param, pfunc, rebuild_collect_shared
from theano.compile.function.types import (
AliasedMemoryError,
Function,
FunctionMaker,
Supervisor,
UnusedInputError,
alias_root,
check_equal,
convert_function_input,
fgraph_updated_vars,
get_info_on_inputs,
infer_reuse_pattern,
insert_deepcopy,
orig_function,
register_checker,
std_fgraph,
view_tree_set,
)
from theano.compile.io import In, Out, SymbolicInput, SymbolicOutput
from theano.compile.mode import (
FAST_COMPILE,
FAST_RUN,
JAX,
OPT_FAST_COMPILE,
OPT_FAST_RUN,
OPT_FAST_RUN_STABLE,
OPT_MERGE,
OPT_NONE,
OPT_O2,
OPT_O3,
OPT_STABILIZE,
OPT_UNSAFE,
AddDestroyHandler,
AddFeatureOptimizer,
Mode,
PrintCurrentFunctionGraph,
get_default_mode,
get_mode,
instantiated_default_mode,
local_useless,
optdb,
predefined_linkers,
predefined_modes,
predefined_optimizers,
register_linker,
register_mode,
register_optimizer,
)
from theano.compile.monitormode import MonitorMode
from theano.compile.ops import (
DeepCopyOp,
......@@ -25,6 +70,5 @@ from theano.compile.ops import (
specify_shape,
view_op,
)
from theano.compile.pfunc import Param, pfunc, rebuild_collect_shared
from theano.compile.profiling import ProfileStats, ScanProfileStats
from theano.compile.sharedvalue import SharedVariable, shared, shared_constructor
......@@ -5,9 +5,9 @@ from functools import partial, reduce
import theano
from theano import gof
from theano.compile.function_module import orig_function
from theano.compile.function.pfunc import rebuild_collect_shared
from theano.compile.function.types import orig_function
from theano.compile.mode import optdb
from theano.compile.pfunc import rebuild_collect_shared
from theano.compile.sharedvalue import SharedVariable
from theano.gof import Variable, ops_with_inner_function
from theano.gof.graph import io_connection_pattern
......@@ -116,7 +116,7 @@ class OpFromGraph(gof.Op):
\*\*kwargs : optional
Check
:func:`orig_function <theano.compile.function_module.orig_function>`
:func:`orig_function <theano.compile.function.types.orig_function>`
for more arguments, only works when not inline.
......
......@@ -18,7 +18,7 @@ import numpy as np
import theano
from theano import change_flags, config, gof
from theano.compile.function_module import (
from theano.compile.function.types import (
Function,
FunctionMaker,
infer_reuse_pattern,
......@@ -2493,7 +2493,7 @@ class _Maker(FunctionMaker): # inheritance buys a few helper functions
with change_flags(compute_test_value=config.compute_test_value_opt):
optimizer(fgraph)
theano.compile.function_module.insert_deepcopy(
theano.compile.function.types.insert_deepcopy(
fgraph, inputs, list(chain(outputs, additional_outputs))
)
......@@ -2707,7 +2707,7 @@ class DebugMode(Mode):
"""
# This function will be used to create a FunctionMaker in
# function_module.function
# function.types.function
def function_maker(self, i, o, m, *args, **kwargs):
"""
Return an instance of `_Maker` which handles much of the debugging work.
......
"""
Define the `function` function.
"""
import logging
import re
import traceback as tb
import warnings
from collections import OrderedDict
from theano.compile.function_module import orig_function
from theano.compile.pfunc import pfunc
from theano.compile.function.pfunc import pfunc
from theano.compile.function.types import orig_function
__all__ = ["types", "pfunc"]
__docformat__ = "restructuredtext en"
_logger = logging.getLogger("theano.compile.function")
......@@ -104,7 +100,7 @@ def function(
on_unused_input=None,
):
"""
Return a :class:`callable object <theano.compile.function_module.Function>`
Return a :class:`callable object <theano.compile.function.types.Function>`
that will calculate `outputs` from `inputs`.
Parameters
......@@ -162,7 +158,7 @@ def function(
Returns
-------
:class:`theano.compile.function_module.Function` instance
:class:`theano.compile.function.types.Function` instance
A callable object that will compute the outputs (given the inputs) and
update the implicit function arguments according to the `updates`.
......
......@@ -7,14 +7,14 @@ import logging
import warnings
from theano import config
from theano.compile.function_module import UnusedInputError, orig_function
from theano.compile.function.types import UnusedInputError, orig_function
from theano.compile.io import In, Out
from theano.compile.profiling import ProfileStats
from theano.compile.sharedvalue import SharedVariable, shared
from theano.gof import Constant, Variable
_logger = logging.getLogger("theano.compile.pfunc")
_logger = logging.getLogger("theano.compile.function.pfunc")
__docformat__ = "restructuredtext en"
......@@ -389,8 +389,8 @@ def pfunc(
"""
#
# This function works by cloning the graph (except for the
# inputs), and then shipping it off to compile.function (There it
# will be cloned again, unnecessarily, because it doesn't know
# inputs), and then shipping it off to theano.compile.function.function
# (There it will be cloned again, unnecessarily, because it doesn't know
# that we already cloned it.)
#
# First, it clones the replacements named in the givens argument,
......
......@@ -23,7 +23,7 @@ from theano.gof.op import ops_with_inner_function
from theano.gof.toolbox import is_same_graph
_logger = logging.getLogger("theano.compile.function_module")
_logger = logging.getLogger("theano.compile.function.types")
__docformat__ = "restructuredtext en"
......
......@@ -9,7 +9,7 @@ import warnings
import theano
import theano.gof.vm
from theano import config, gof
from theano.compile.function_module import Supervisor
from theano.compile.function.types import Supervisor
from theano.sandbox.jax_linker import JAXLinker
......@@ -124,7 +124,7 @@ class AddDestroyHandler(gof.Optimizer):
if not supervisor_added:
warnings.warn(
"WARNING: Supervisor is not added. Please build a FunctionGraph"
"via theano.compile.function_module.std_graph()"
"via theano.compile.function.types.std_graph()"
"or add the Supervisor class manually.",
stacklevel=3,
)
......
......@@ -60,7 +60,7 @@ def d3viz(fct, outfile, copy_deps=True, *args, **kwargs):
Parameters
----------
fct : theano.compile.function_module.Function
fct : theano.compile.function.types.Function
A compiled Theano function, variable, apply or a list of variables.
outfile : str
Path to output HTML file.
......@@ -119,7 +119,7 @@ def d3write(fct, path, *args, **kwargs):
Parameters
----------
fct : theano.compile.function_module.Function
fct : theano.compile.function.types.Function
A compiled Theano function, variable, apply or a list of variables.
path: str
Path to output file
......
......@@ -104,7 +104,7 @@ class PyDotFormatter:
Parameters
----------
fct : theano.compile.function_module.Function
fct : theano.compile.function.types.Function
A compiled Theano function, variable, apply or a list of variables.
graph: pydot.Dot
`pydot` graph to which nodes are added. Creates new one if
......
......@@ -234,7 +234,7 @@ def fast_inplace_check(inputs):
"""
fgraph = inputs[0].fgraph
Supervisor = theano.compile.function_module.Supervisor
Supervisor = theano.compile.function.types.Supervisor
protected_inputs = [
f.protected for f in fgraph._features if isinstance(f, Supervisor)
]
......
......@@ -68,9 +68,9 @@ class Apply(Node):
This class is typically instantiated by a `PureOp.make_node` method, which
is called by `PureOp.__call__`.
The driver `theano.compile.function` uses `Apply.inputs` together with
`Variable.owner` to search the expression graph and determine which inputs
are necessary to compute the function's outputs.
The function `theano.compile.function.function` uses `Apply.inputs`
together with `Variable.owner` to search the expression graph and determine
which inputs are necessary to compute the function's outputs.
A `Linker` uses the `Apply` instance's `op` field to compute numeric values
for the output variables.
......@@ -373,10 +373,6 @@ class Variable(Node):
`Variable`. The `Variable` referred to by `a` is also an instance of
`Constant`.
`compile.function` uses each `Apply` instance's `inputs` attribute together
with each Variable's `owner` field to determine which inputs are necessary
to compute the function's outputs.
"""
# __slots__ = ['type', 'owner', 'index', 'name']
......
......@@ -3204,7 +3204,7 @@ def check_stack_trace(f_or_fgraph, ops_to_check="last", bug_print="raise"):
Parameters
----------
f_or_fgraph: theano.compile.function_module.Function or
f_or_fgraph: theano.compile.function.types.Function or
theano.gof.fg.FunctionGraph
The compiled function or the function graph to be analysed.
ops_to_check: it can be of four different types:
......@@ -3233,7 +3233,7 @@ def check_stack_trace(f_or_fgraph, ops_to_check="last", bug_print="raise"):
True if the outputs of the specified ops have a stack, False otherwise.
"""
if isinstance(f_or_fgraph, theano.compile.function_module.Function):
if isinstance(f_or_fgraph, theano.compile.function.types.Function):
fgraph = f_or_fgraph.maker.fgraph
elif isinstance(f_or_fgraph, theano.gof.fg.FunctionGraph):
fgraph = f_or_fgraph
......
差异被折叠。
......@@ -48,8 +48,10 @@ from collections import OrderedDict
import numpy as np
import theano.tensor as tt
from theano import compile, config, gof
from theano.compile import SharedVariable, function, ops
from theano import config, gof
from theano.compile import SharedVariable, ops
from theano.compile.function import function
from theano.compile.mode import Mode
from theano.gof.utils import TestValueError
from theano.scan_module import scan_op, scan_utils
from theano.scan_module.scan_utils import safe_new, traverse
......@@ -861,7 +863,7 @@ def scan(
dummy_args,
dummy_outs,
updates=updates,
mode=compile.mode.Mode(linker="py", optimizer=None),
mode=Mode(linker="py", optimizer=None),
on_unused_input="ignore",
profile=False,
)
......
......@@ -58,7 +58,8 @@ import numpy as np
import theano
from theano import compile, config, gof, gradient, tensor
from theano.compile import In, Out, function
from theano.compile.function import function
from theano.compile.io import In, Out
from theano.compile.mode import AddFeatureOptimizer
from theano.compile.profiling import ScanProfileStats
from theano.gof import Apply, PureOp
......@@ -1703,7 +1704,7 @@ class Scan(PureOp):
o_s.storage[0] = None
t_call = time.time() - t0_call
# NOTE: make this match what's in function_module.Function
# NOTE: make this match what's in function.types.Function
# and this little string helps us to find this spot:
# "PROFILE_CODE"
......
......@@ -60,7 +60,7 @@ import numpy as np
import theano
from theano import gof, scalar, tensor
from theano.compile import optdb
from theano.compile.function_module import deep_copy_op
from theano.compile.function.types import deep_copy_op
from theano.gof import DestroyHandler, InconsistencyError, toolbox
from theano.gof.graph import equal_computations
from theano.gof.opt import Optimizer, pre_constant_merge, pre_greedy_local_optimizer
......
......@@ -27,7 +27,7 @@ import numpy as np
import theano
from theano import gof, scalar, tensor
from theano.compile.pfunc import rebuild_collect_shared
from theano.compile.function.pfunc import rebuild_collect_shared
from theano.gof.utils import TestValueError
from theano.tensor.basic import get_scalar_constant_value
......
......@@ -307,7 +307,7 @@ class InplaceElemwiseOptimizer(Optimizer):
protected_inputs = [
f.protected
for f in fgraph._features
if isinstance(f, theano.compile.function_module.Supervisor)
if isinstance(f, theano.compile.function.types.Supervisor)
]
protected_inputs = sum(protected_inputs, []) # flatten the list
protected_inputs.extend(fgraph.outputs)
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论